等待 ngOnInit 在 Jasmine Angular2 中完成
Wait for ngOnInit to finish in Jasmine 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; });
}
当我 运行 我得到的测试:
Expected undefined to equal 'Crazypug'
如何让 Jasmine 等待 ngOnInit 函数完成?
我在 SO 上找到了一些解决方案,但是从很久以前开始(以 angular2 时间而言)。它们非常复杂或过时。
您应该将 async
函数替换为 fakeAsync
import {..., tick, fakeAsync} from '@angular/core/testing';
...
fakeAsync(inject([NavComponent], (component) => {
component.ngOnInit();
tick();
expect(component.firstName).toEqual('Crazypug')
}))
我正在对一个组件进行单元测试,这就是我所拥有的:
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; });
}
当我 运行 我得到的测试:
Expected undefined to equal 'Crazypug'
如何让 Jasmine 等待 ngOnInit 函数完成? 我在 SO 上找到了一些解决方案,但是从很久以前开始(以 angular2 时间而言)。它们非常复杂或过时。
您应该将 async
函数替换为 fakeAsync
import {..., tick, fakeAsync} from '@angular/core/testing';
...
fakeAsync(inject([NavComponent], (component) => {
component.ngOnInit();
tick();
expect(component.firstName).toEqual('Crazypug')
}))