在 karma 中测试订阅给出错误 'Observable<>' 类型的参数不能分配给 'Subscription' 类型的参数

testing subscribe in karma gives error Argument of type 'Observable<>' is not assignable to parameter of type 'Subscription'

我有这个方法

loadCombos(): void {
  this.combosService.accounts$.subscribe(
    (data: any) => {
    this.list = data;
      }
    }
  );
}

这是我当前的测试:

it('should test loadCombos executions ', (done) => {
  combosService = TestBed.inject(CombosService);
  spyOn(combosService.accounts$, 'subscribe').and.returnValue(of(mockList));
  component.loadCombos();
  expect(component.list).not.toBeNull();

  done();
});

如何在我的测试中使用 mockList,目前我得到的是一个可观察的但它需要一个订阅,但我不知道如何去做。

这里有几个错误。

一个 subscribe() 不是 return 一个 Observable 它 return 是一个 Subscription 就像错误说的那样。您可以在测试中 return new Subscription() 但这没有任何意义。

如果您想模拟 accounts$ 的 return。正确的方法是为模拟实现更改 CombosServiceTake a look at the documentation.

一个快速的测试方法是直接覆盖accounts(如果它没有被标记为只读)


it('should test loadCombos executions ', (done) => {
  combosService = TestBed.inject(CombosService);
  combosService.accounts$ =  of(mockList);
  component.loadCombos();
  expect(component.list).not.toBeNull();

  done();
});

不过我不会这样做,因为如果 loadCombos() 是从某种按钮调用的,则该实现是错误的。

编辑:我个人喜欢在 fakeAsync 调用中测试 observables:https://angular.io/api/core/testing/fakeAsync