等待ngOnInit在Jasmine Angular2中完成

时间:2016-07-15 08:30:05

标签: angular jasmine karma-jasmine

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

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的方式)。他们非常复杂或过时。

1 个答案:

答案 0 :(得分:16)

您应该替换async

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