我正在測試一個組件,它會在調用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被更新。