wapo
wapo

Reputation: 25

How to reach catchError operator with testing

I'm trying to cover catchError blocks from my code but I tried many approaches and none of them actually works. My code is properly covered except all catchError blocks! Is there some magic function that I would not know ?

Here is some sample code.

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();
  });

EDIT: The spec file above is just one of the many snippets I tried and I don't get why this is not working. Any advice would be mad appreciated. Also, I can get the catchError to be tested with effects.get$.subscribe but for some reason it's skipped on code coverage which is an issue for this case.

Thanks a bunch!

Upvotes: 0

Views: 3860

Answers (1)

satanTime
satanTime

Reputation: 13584

use throwError instead of of

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

Upvotes: 2

Related Questions