Angular 使用 *ngIf 测试 DOM 个元素
Angular testing DOM elements with *ngIf
为什么这个测试通过了
it ('should hide datatable if data is undefined', () => {
component.DATA = undefined;
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('app-datatable'))).toBeNull();
});
但这不是
it ('should hide datatable if data is undefined', () => {
component.DATA = undefined;
const datatable = fixture.debugElement.query(By.css('app-datatable'));
fixture.detectChanges();
expect(datatable).toBeNull();
});
对于第二个测试套件,我收到以下错误
错误:预期 DebugElement__POST_R3__({ nativeNode: }) 为空。
这是DOM
的代码
<app-datatable *ngIf="DATA"></app-datatable>
这与你运行Angular的变化检测方式有关:
在第一个测试中,您 运行 fixture.detectChanges()
刚刚更改 component.DATA
,我想这会在视图中进行一些更改。
在第二个测试中,您首先查询 app-datatable
元素,然后调用 fixture.detectChanges()
。有了这个 secuence,我假设 datatable
有一些内容,然后它在你调用 detectChanges()
后发生变异,但是因为你在更改检测之前访问它,所以测试失败。
为什么这个测试通过了
it ('should hide datatable if data is undefined', () => {
component.DATA = undefined;
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('app-datatable'))).toBeNull();
});
但这不是
it ('should hide datatable if data is undefined', () => {
component.DATA = undefined;
const datatable = fixture.debugElement.query(By.css('app-datatable'));
fixture.detectChanges();
expect(datatable).toBeNull();
});
对于第二个测试套件,我收到以下错误
错误:预期 DebugElement__POST_R3__({ nativeNode: }) 为空。
这是DOM
的代码<app-datatable *ngIf="DATA"></app-datatable>
这与你运行Angular的变化检测方式有关:
在第一个测试中,您 运行
fixture.detectChanges()
刚刚更改component.DATA
,我想这会在视图中进行一些更改。在第二个测试中,您首先查询
app-datatable
元素,然后调用fixture.detectChanges()
。有了这个 secuence,我假设datatable
有一些内容,然后它在你调用detectChanges()
后发生变异,但是因为你在更改检测之前访问它,所以测试失败。