【问题标题】:How to reach catchError operator with testing如何通过测试到达 catchError 运算符
【发布时间】:2020-05-08 07:07:05
【问题描述】:

我试图从我的代码中覆盖catchError 块,但我尝试了很多方法,但它们都没有真正起作用。除了所有 catchError 块之外,我的代码都被正确覆盖了!有什么我不知道的神奇功能吗?

这是一些示例代码。

some.effects.ts

 get$ = createEffect(() =>
  this.actions$.pipe(
    ofType(myActions.Get),
    switchMap(({ payload }) => {
      return this.httpService.get(payload).pipe(
        map(res => myActions.Loaded({ payload: res })),
        catchError(() => {
          localStorage.removeItem('someItem');
          return of(myActions.Create()))
        }
      );
    })
  )

);

some.effects.spec.ts

  it('get$ fails', () => {

    function mockError() {
      return new HttpErrorResponse({
        error: 'error', 
        headers: new HttpHeaders(),
        status: 404
      });
    }

    spyOn(httpService, 'get').and.returnValue(of(mockError));

    actions$ = hot('--a', { a: myActions.Get({}) });
    completion$ = cold('--c', { c: myActions.Create({}) });

    expect(effects.get$).toBeObservable(completion$);
    expect(localStorage.removeItem).toHaveBeenCalled();
  });

编辑:上面的规范文件只是我尝试过的众多 sn-ps 之一,我不明白为什么这不起作用。任何建议将不胜感激。此外,我可以使用 effects.get$.subscribe 测试 catchError,但由于某种原因,它在代码覆盖率上被跳过,这对于这种情况来说是一个问题。

非常感谢!

【问题讨论】:

    标签: unit-testing rxjs karma-jasmine


    【解决方案1】:

    使用throwError 代替of

    spyOn(httpService, 'get').and.returnValue(throwError(mockError));
    

    【讨论】:

    • 有效!这太疯狂了,我一直在尝试 throwError 但不是那样...为什么spyOn(...).and.throwError() 不起作用?
    • 因为.and.throwErrorjasmine 的一部分,与rxjs 没有任何关系。 throwError 是一个 rxjs 创建函数,它创建一个流,该流会立即引发订阅错误。
    猜你喜欢
    • 2020-12-12
    • 2022-01-14
    • 2012-08-21
    • 2019-07-31
    • 2014-04-28
    • 1970-01-01
    • 2020-09-18
    • 2018-10-22
    • 1970-01-01
    相关资源
    最近更新 更多