等待ngOnInit在Jasmine Angular2中完成

sti*_*rts 17 jasmine karma-jasmine angular

我正在对一个组件进行单元测试,这就是我所拥有的:

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')
    }))
  );

});
Run Code Online (Sandbox Code Playgroud)

这是ngOnInit函数:

ngOnInit() {
    this.userService.getFirstNameCall().subscribe(
      data => {this.firstName = data.firstname; });
}
Run Code Online (Sandbox Code Playgroud)

当我运行测试时,我得到:

预期未定义为等于'Crazypug'

我怎样才能让Jasmine等待ngOnInit函数完成?我从很久以前就在SO上找到了一些解决方案(以角度2的方式).他们非常复杂或过时.

Ole*_*nov 16

你应该替换async函数fakeAsync

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