【问题标题】:testing subscribe in karma gives error Argument of type 'Observable<>' is not assignable to parameter of type 'Subscription'在 karma 中测试订阅会给出错误“Observable<>”类型的参数不能分配给“订阅”类型的参数
【发布时间】:2020-12-04 12:21:30
【问题描述】:

我有这个方法

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,目前我得到了一个 observable 但它需要订阅,但我不知道该怎么做。

【问题讨论】:

    标签: angular unit-testing testing jasmine karma-jasmine


    【解决方案1】:

    这里有几个错误。

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

    如果你想模拟你的accounts$ 的返回。正确的方法是将CombosService 更改为模拟实现。 Take 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

    【讨论】:

    • 我也试过了,我收到以下错误:'"accounts$"' 类型的参数不可分配给'never' 类型的参数。这是一个继承项目,我必须做测试,我没有太多选择,不能引入新东西,所以我不能使用 fakeasync
    • fakeAsync 已经随 Angular 一起提供,没有什么可改变的。另外我刚刚意识到accounts$ 不是一个函数。对不起
    • @monxas 现在看看
    猜你喜欢
    • 1970-01-01
    • 2020-09-08
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    • 2016-11-12
    • 1970-01-01
    相关资源
    最近更新 更多