【发布时间】:2017-08-26 06:08:14
【问题描述】:
我正在测试一个组件,当调用 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>
*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 被更新。
【问题讨论】: