2016-07-15 60 views
12

我的單元測試的組成部分,這是我所:等待ngOnInit在茉莉花Angular2完成

describe('Component: nav',() => { 

    beforeEach(() => addProviders([ 
    provide(UserService, {useClass: MockUserService}), 
    NavComponent 
    ])); 

    it('should have a property \'firstName\' with the value \'Crazypug\'', 
    async(inject([NavComponent], (component) => { 
     component.ngOnInit(); 
     expect(component.firstName).toEqual('Crazypug') 
    })) 
); 

}); 

這是ngOnInit功能:

ngOnInit() { 
    this.userService.getFirstNameCall().subscribe(
     data => {this.firstName = data.firstname; }); 
} 

當我運行測試我得到:

預期不確定等於 'Crazypug'

如何讓Jasmine等待ngOnInit函數完成? 我發現了一些SO的解決方案,但很久以前(以角度2的方式)。他們非常複雜或過時。

回答

12

此時應更換async功能fakeAsync

import {..., tick, fakeAsync} from '@angular/core/testing'; 
... 
fakeAsync(inject([NavComponent], (component) => { 
    component.ngOnInit(); 
    tick(); 
    expect(component.firstName).toEqual('Crazypug') 
})) 
+0

我ngOnInit調用http.get(通過服務方法),並在返回時,數據將接收到的值。如果我將測試代碼包裝在setTimeout中,它會成功,但tick方法似乎不起作用(即使提供了與setTimeout值相同的超時值)。不知道爲什麼 – Nitin