2017-05-29 76 views
1

我有一個異步工作的ngOnInit方法。如何在測試前等待異步ngOninit完成

異步工作完成後,如何執行我的expect語句?

it('test things once all the promises declared in ngOninit are resolved',() => { 
    comp.ngOnInit(); 

    // I want to test that comp.property is like expected 

}); 

我的組件的方法是這樣的:

OnInit() { 
    this.asyncMethod(); 
}; 

asyncMethod() { 
    this.methodThatReturnsPromise().then(() => { 
    this.property = this.otherPropertyNowResolved; 
    }) 
}; 
+1

如何在任何程序中其他人知道這是完成時?你可以檢查回調內部發生了什麼? – jonrsharpe

+0

在回調中有一些初始化邏輯 – Lev

+0

您可以擴展一下嗎?給一個[mcve]。 – jonrsharpe

回答

4
fixture = TestBed.createComponent(MyComponent); 


it('test things once all the promises declared in ngOninit are resolved', async(() => { 
     fixture.detectChanges(); 
     fixture.whenStable().then(
        () => { 
         // This should run once ngOnInit is completed 

        } 
       ); 
})); 
+0

在解決了ngOnint中的所有承諾後,該回調不運行 – Lev

+0

根據您提供的信息,這就是我所取得的成果。請顯示更多關於配置的代碼或嘗試正確調試。並且不需要調用'comp.ngOnInit();'顯式地 –

+0

https://angular.io/docs/ts/latest/guide/testing.html#!#when-stable –