查询单元测试中的自定义角度组件

时间:2018-01-17 17:45:09

标签: angular unit-testing jasmine

我可以在单元测试中查询自定义Angular组件吗?

例如,我有以下组件:

<div class="my-custom-checkbox-group">
    <my-checkbox
        class="my-custom-checkbox" 
        (click)="onClick()">
    </my-checkbox>
    <span>...</span>
</div>

在我的单元测试中,我正在尝试执行以下操作:

it('should mark field as disabled when checkbox is ticked', async(() => {
    // Arrange
    fixture.detectChanges();
    de = fixture.debugElement.query(By.css('.my-custom-checkbox-class'));

    const field: AbstractControl = component.myForm.controls['myField'];

    // Act
    el.click();

    // Assert
    expect(field.valid).toBeFalsy();
}));

但我明白了:

  

TypeError:无法读取属性&#39; nativeElement&#39;为null

思考?感谢

1 个答案:

答案 0 :(得分:0)

你在css之后缺少一个点(。)(&#39; .my-custom-checkbox-class&#39;)。 试试de = fixture.debugElement.query(By.css('.my-custom-checkbox-class'));

首先要做的事情是:当您使用async时,您需要拨打expect

fixture.whenStable().then(() => { // wait for async getQuote fixture.detectChanges(); // update view with quote expect(el.textContent).toBe(testQuote); });

您可以拨打fakeAsync而不是async,而不是fixture.whenStable().then即可。

tick(); fixture.detectChanges();

it('should mark field as disabled when checkbox is ticked', fakeAsync(() => {
     tick();
    fixture.detectChanges();
    de = fixture.debugElement.query(By.css('.my-custom-checkbox-class'));

    de.triggerEventHandler('click', null);

    tick();
    fixture.detectChanges();

    // Assert
}));
相关问题