2017-07-24 77 views
0

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

回答

2

我有一個類似的問題,這個解決方案爲我工作:

我叫fixture.autoDetectChanges(true);代替(或補充)fixture.detectChanges()