How to write unit test for effect when it fails in angular

49 views Asked by At

I have loadUserCacheRequestEffect$ effect

loadUserCacheRequestEffect$ = createEffect(() =>
  this.actions$.pipe(
    ofType(ActionTypes.USER_SESSION_CACHE_REQUEST),
    switchMap(() => this.taskCacheKeyService.getCacheUserSessionData()
    .pipe(
        switchMap((sessionData: TaskCacheKey) => [
          ActionTypes.USER_SESSION_CACHE_SUCCESS({ sessionData }),
          ActionTypes.TASK_DETAILS_REQUEST({
            taskId: sessionData.taskId,
            templateNumber: sessionData.templateId
          })
        ]),
        catchError((err) => {
          return of(ActionTypes.USER_SESSION_CACHE_FAILURE({error: err.error.detail}));
        })
      ))
    )
  );

I have write unit test for success case that is working

it('loadUserCacheRequestEffect should return USER_SESSION_CACHE_SUCCESS and TASK_DETAILS_REQUEST actions', () => {
    actions$ = hot('a', { a: fromActions.USER_SESSION_CACHE_REQUEST() });
    const expected = cold('(bc)', {
      b: fromActions.USER_SESSION_CACHE_SUCCESS({
        sessionData: userSessionDataMock
      }),
      c: fromActions.TASK_DETAILS_REQUEST({
        taskId: userSessionDataMock.taskId,
        templateNumber: userSessionDataMock.templateId
      })
    });
    expect(effects.loadUserCacheRequestEffect$).toBeObservable(expected);
  });

I would like to write unit test when effect fail and return ActionTypes.USER_SESSION_CACHE_FAILURE({error: err.error.detail})

2

There are 2 answers

0
dev verma On

This is working example after some correction:

it('it should handle error', () => {
        actions$ = hot('a', {a: fromActions.USER_SESSION_CACHE_REQUEST()});
        const taskCacheKeyServiceSpy = spyOn(taskCacheKeyService, 'getCacheUserSessionData');
        taskCacheKeyServiceSpy.and.returnValue(cold('-#', {}, {error: {detail: 'something'}}));
        const expected = cold('-b', {
          b: fromActions.USER_SESSION_CACHE_FAILURE({error: 'something'})
        });
        expect(effects.loadUserCacheRequestEffect$).toBeObservable(expected);
      });
2
Buczkowski On

That should do the job if not then you have to align marbles:

  it('should handle error', () => {
    actions$ = hot('a', {a: fromActions.USER_SESSION_CACHE_REQUEST()});
    taskCacheKeyServiceSpy.getCacheUserSessionData.and.returnValue(cold('-#', {}, {error: {details: 'something'}}));

    const expected = cold('-b', {
      c: ActionTypes.USER_SESSION_CACHE_FAILURE({error: err.error.detail})
    });

    expect(effects.loadUserCacheRequestEffect).toBeObservable(expected);
  });