在 dom 由打字稿操作的组件中创建 Angular 单元测试

Create Angular unit tests in components where the dom is manipulated by the typescript

提问人:Salvatore Lorello 提问时间:11/15/2023 更新时间:11/16/2023 访问量:28

问:

我正在努力在 Angular 16 中创建一个 ui 库,当我在打字稿中创建组件(例如 textarea)时,我会在逻辑级别上操作元素的 dom,没有问题,但是当我尝试编写测试时,代码总是在存在 dom 的行中中断。

如何为以下情况编写测试?

TS :

@ViewChild('myTextarea') myTextarea!: ElementRef<HTMLTextAreaElement>;

@Input() placeholderLabel?: string = 'label';
@Input() helperText?: string;
@Input() formGroup?: FormGroup;
@Input() formControlName?: string;
@Input() name: string;
@Input() disabled: boolean = false;
@Input() isWrongInput: boolean = false; // deprecated
@Input() hasError: boolean = false;

showHelperText: boolean = false;
showName: boolean = false;
tempPlaceholder: string = '';
ngOnInit(): void {
    if (this.helperText) {
        this.showHelperText = true;
    }
    this.tempPlaceholder = this.placeholderLabel;
}

onFocus() {
    if (!this.disabled) {
        this.showName = true;
        this.placeholderLabel = '';
    }

}
onBlur(event: any) {
    if (!this.disabled) {
        if (event.target.value == "") {
            this.showName = false;
            this.placeholderLabel = this.tempPlaceholder;
        }
    }
}
autoResizeTextarea() {
    const textarea = this.myTextarea.nativeElement;
    textarea.style.height = 'auto'; // Imposta l'altezza su 'auto' per calcolare la dimensione corretta
    textarea.style.height = `${textarea.scrollHeight}px`; // Imposta l'altezza basata sulla dimensione del contenuto

    if (textarea.style.height !== '44px') {
        textarea.style.lineHeight = '24px';
        this.autoResizeTextarea();
        if (textarea.style.height === '80px') {
            textarea.style.lineHeight = '52px';
        }
    }
    if (textarea.style.height === '44px' || textarea.style.height === undefined) {
        textarea.style.lineHeight = '38px';
    }
  }
  }

我的规格测试

enter code here
 describe('CaInputTextComponent', () => {
let component: CaTextAreaComponent;
let fixture: ComponentFixture<CaTextAreaComponent>;


beforeEach(() => {
    TestBed.configureTestingModule({
        imports: [
            CaTextAreaComponent,

        ],


    });

    fixture = TestBed.createComponent(CaTextAreaComponent);
    component = fixture.componentInstance;



});

//Test per verificare la creazione di un componente
it('Dovrebbe creare il componente', () => {
    expect(component).toBeTruthy();
});

//Test per verificare se viene mostrata la label nel template
it('Dovrebbe mostrare la label nel template', () => {
    component.placeholderLabel = 'Test';
    fixture.detectChanges();
    const labelElement = fixture.nativeElement.querySelector('.input');
    expect(labelElement.placeholder).toContain('Test');
});

//Test click evento onFocus
it('Dovrebbe emettere evento click con il corrretto valore', () => {
    const labelElement = fixture.nativeElement.querySelector('.input');
    component.placeholderLabel = 'Test';
    component.onFocus();
    expect(component.placeholderLabel).toEqual('');
    expect(labelElement.placeholder).toEqual('');

});


//Test click evento onBlur
it('Dovrebbe emettere evento click con il corrretto valore', () => {
    const labelElement = fixture.nativeElement.querySelector('.input');
    const event = {
        target: {
            value: ''
        }
    };
    component.onBlur(event);
    fixture.detectChanges();
    expect(component.showName).toEqual(false);
    expect(labelElement.placeholder).toBe(component.tempPlaceholder);
});


//Test click evento onBlur
it('Dovrebbe emettere evento click con il corrretto valore', () => {
    component.helperText = 'test';
    component.ngOnInit();
    fixture.detectChanges();
    expect(component.helperText).toEqual('test');
    expect(component.showHelperText).toEqual(true);
});

it('should resize textarea properly', () => {
    component.myTextarea.nativeElement.value = 'Sss';
    component.autoResizeTextarea();
    expect(component.myTextarea.nativeElement.style.height).toBe(`${component.myTextarea.nativeElement.scrollHeight}px`);
    // Add other expectations based on your specific requirements
});


 });

我的错误 TypeError:无法读取 undefined 的属性(读取“nativeElement”) 在 UserContext.apply (projects/lib/src/lib/components/ca-textarea/ca-textarea.component.spec.ts:76:30)

线路误差: component.myTextarea.nativeElement.value = 'sss';

angular typescript 单元测试 dom karma-jasmine

评论

0赞 Pieterjan 11/16/2023
我认为你应该用于 dom 操作,以保护角度普遍的水合作用Renderer2

答:

0赞 Snincent 11/16/2023 #1

用于查询 HTML 应该使其工作。fixture.debugElement.query(...).nativeElement