Angular 角度2测试,未检测到模板更新

Angular 角度2测试,未检测到模板更新,angular,angular2-testing,Angular,Angular2 Testing,我正在测试一个组件,当调用ngAfterViewInit生命周期钩子时,该组件会自动在其模板中插入一个复选框 export class MyComponent { ngAfterViewInit() { // checkbox insertion in the template here ... } ... } 这是我的测试: it('should inject the checkbox', () => { fixture = TestBed.crea

我正在测试一个组件,当调用ngAfterViewInit生命周期钩子时,该组件会自动在其模板中插入一个复选框

export class MyComponent {

  ngAfterViewInit() {
    // checkbox insertion in the template here
    ...
  }

  ...
}
这是我的测试:

it('should inject the checkbox', () => {
  fixture = TestBed.createComponent(AutogeneratedTableComponent);
  fixture.detectChanges();

  rows = fixture.debugElement.queryAll(By.css('tr'));
  console.log(Object.assign({}, rows[1].nativeElement));  // *referenceLog
  console.log(rows[1].nativeElement));  // *cloneLog

  expect(rows[1].query(By.css('input')).not.toBeNull(); // FAILS
}
*refereceLog打印不带插入td的tr

<tr ng-reflect-id="22" id="22">
   <td>Single Room</td>
   <td>My single room.</td>
</tr>
我尝试手动调用ngAfterViewInit

it('should inject the checkbox', () => {
  fixture = TestBed.createComponent(AutogeneratedTableComponent);
  fixture.detectChanges();

  fixture.debugElement.componentInstance.ngAfterViewInit();
  fixture.detectChanges();

  rows = fixture.debugElement.queryAll(By.css('tr'));
  console.log(Object.assign({}, rows[1].nativeElement));  // *referenceLog
  console.log(rows[1].nativeElement));  // *cloneLog

  expect(rows[1].query(By.css('input')).not.toBeNull(); // FAILS
}
*refereceLog打印预期的tr

<tr ng-reflect-id="22" id="22">
   <td><input id="22" type="checkbox"></td>
   <td>Single Room</td>
   <td>My single room.</td>
</tr>
*克隆日志中没有更改

然后我试着

添加间谍组件, “ngAfterViewInit”.andReturnValuePromise.resolvetrue.and.callThrough; 然后是spyOn.calls.mostRecent.returnValue.then=> {fixture.detectChanges…}在 街区

向单个测试声明添加async并执行 fixture.whenStable.then内的求值=>{ fixture.detectChanges…}

将fakeAsync添加到单个测试声明和一个勾号 评估前打电话

所有尝试都具有相同的先前结果。评估完成后,将更新模板元素


我应该找到一种方法来停止测试执行,直到我正在测试的nativeElement更新。

我遇到了类似的问题,这个解决方案对我有效:


我调用fixture.autoDetectChangestrue;代替fixture.detectChanges或作为fixture.detectChanges的补充

我有一个类似的问题,这个解决方案对我很有效:


我调用fixture.autoDetectChangestrue;代替fixture.detectChanges或作为fixture.detectChanges的补充

真棒,经过几个小时的搜索,找到了这个答案。你能指出你在哪里找到这个建议的任何文件吗?Thankstill对Angular 9 awesome有效,经过几个小时的搜索,找到了这个答案。你能指出你在哪里找到这个建议的任何文件吗?谢谢,有效期为9天
<tr ng-reflect-id="22" id="22">
   <td><input id="22" type="checkbox"></td>
   <td>Single Room</td>
   <td>My single room.</td>
</tr>