【问题标题】:Wait for ngOnInit to finish in Jasmine Angular2等待 ngOnInit 在 Jasmine Angular2 中完成
【发布时间】:2016-07-15 08:30:05
【问题描述】:

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

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 上找到了一些解决方案,但从很久以前(以 angular2 时间而言)。它们非常复杂或过时。

【问题讨论】:

    标签: angular jasmine karma-jasmine


    【解决方案1】:

    您应该将async 函数替换为fakeAsync

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

    【讨论】:

    • 我的 ngOnInit 调用一个 http.get(通过服务方法)并在它返回时将数据设置为接收到的值。如果我将测试代码包装在 setTimeout 中,它会成功,但 tick 方法似乎不起作用(即使提供与 setTimeout 值相同的超时。不知道为什么
    猜你喜欢
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 2014-10-25
    • 1970-01-01
    • 2019-11-05
    相关资源
    最近更新 更多