Typescript(Angular):单元测试订阅

6 unit-testing jasmine typescript angular

我有一个简单的功能来做到这一点

ngOnInit() {
  if (this.session.getToken()) {
    this.isUserLogged = true;
  }

  this.loadingObserver = this.session.loadingObservable.subscribe(loading => this.isLoading = loading);
}
Run Code Online (Sandbox Code Playgroud)

我的测试如下

it('Testing ngOnInit() ...', async(() => {
  let spy = spyOn(services.session, 'getToken').and.returnValue('token');
  services.session.loadingObservable.subscribe(any => expect(component.isLoading).toEqual(false));
  component.ngOnInit();
  expect(component.isUserLogged).toEqual(true);
  expect(spy).toHaveBeenCalled();
}));
Run Code Online (Sandbox Code Playgroud)

但在我的应用程序的代码覆盖范围内,订阅不包括在内.事实上,期待虚假也有效.

您对如何测试订阅有任何想法吗?

小智 -1

订阅时是否调用您的处理程序代码取决于您所订阅的 Observable 的性质——特别是它的“热度”或“冷度”。阅读这个精彩的解释 - https://blog.thoughtram.io/angular/2016/06/16/cold-vs-hot-observables.html - 并查看你的“loadingObservable”在分类中的位置。但我怀疑正如评论中所建议的,您需要强制它在单元测试中触发。