我正在测试一个组件,它会在调用ngAfterViewInit生命周期钩子时在其模板中插入一个复选框。Angular 2测试,未检测到模板更新
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(打印TR没有插入TD)
<tr ng-reflect-id="22" id="22">
<td>Single Room</td>
<td>My single room.</td>
</tr>
* cloneLog(显示在测试模板的时间不准备好)
Object{__zone_symbol__eventTasks: [ZoneTask{zone: ..., runCount: ..., _zoneDelegates: ..., _state: ..., type: ..., source: ..., data: ..., scheduleFn: ..., cancelFn: ..., callback: ..., invoke: ...}]}
我试着手动调用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>
没有改变* cloneLog
然后我试图
添加
spyOn(component, 'ngAfterViewInit').andReturnValue(Promise.resolve(true)).and.callThrough();
然后spyOn().calls.mostRecent.returnValue.then(() => {fixture.detectChanges() ... })
与done()
在 底部块添加
async()
个别测试声明,做 评价内部fixture.whenStable.then(() => { fixture.detectChanges()... })
评估之前添加
fakeAsync()
个别测试的声明和tick()
呼叫
所有尝试结果都一样。评估完成后,模板元素正在更新。
我应该找到一种方法来停止测试执行,直到我测试的nativeElement被更新。