Angular 使用*ngIf对DOM元素进行角度测试

Angular 使用*ngIf对DOM元素进行角度测试,angular,jasmine,karma-jasmine,angular-test,Angular,Jasmine,Karma Jasmine,Angular Test,为什么这次考试通过了 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

为什么这次考试通过了

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_uuuupost_uuuu3_uuu({nativeNode:})应为空

这是DOM的代码

<app-datatable *ngIf="DATA"></app-datatable>

它与运行Angular的更改检测的方式有关:

  • 在第一个测试中,在更改
    component.DATA
    之后,运行
    fixture.detectChanges()
    ,我支持在视图中进行一些更改

  • 在第二个测试中,首先查询
    app datatable
    元素,然后调用
    fixture.detectChanges()
    。在这种情况下,我假设
    datatable
    有一些内容,然后在调用
    detectChanges()
    后它会发生变化,但由于您在变化检测之前访问了它,因此测试失败


我编辑了我的问题。数据用于触发ngIf,我将其设置为未定义,这样组件就不会被渲染。因此,为了正确理解您,您建议第二个测试中的执行顺序为:1。定义数据,2。fixture.detectChanges(),3。查询数据表,4。expect()。