【问题标题】:Jasmine Test Observable complete function in AngularJasmine Test Observable Angular 中的完整功能
【发布时间】:2021-03-04 12:46:23
【问题描述】:

我想在 Jasmine 中测试 rxjs Observable 的“完整”处理程序。

这是我要测试的代码:

  doSomething()
  {
    const subscription = this.service.getObservable().subscribe(
        (next) => {
        //do something
        },
      (error) => {
        //handle error
      },
      () => {
        // do something on complete <== How can I test this function?

      }
    );
  }

我已经通过创建一个间谍为“下一个”处理程序编写了测试:

const spy = spyOn<any>(service, 'getObservable').and.callFake(() => {
  return from(['nextValue']);
})

我通过创建一个引发错误的间谍来为“错误”处理程序编写测试:

const spy = spyOn<any>(service, 'getObservable').and.callFake(() => {
  return throwError(new Error('error message'));
})

问题:如何模拟完整的处理程序?

【问题讨论】:

  • 当我们收到来自service.getObservable() 的成功响应时,是否触发了onComplete 方法。如果我错了,请纠正我?

标签: angular rxjs jasmine


【解决方案1】:

这是您可以使用 jasmine 模拟完整处理程序的方法:

const spy = spyOn<any>(service, 'getObservable').and.callFake(() => {
      return new Observable(subscriber => {
        subscriber.complete();
      });
    });

【讨论】:

  • 像魅力一样工作。非常感谢。
猜你喜欢
  • 2018-04-12
  • 1970-01-01
  • 2018-01-31
  • 2017-08-17
  • 1970-01-01
  • 2023-03-16
  • 2014-12-14
  • 1970-01-01
  • 2020-08-21
相关资源
最近更新 更多