Search code examples
angularngrxngrx-effectsangular-unit-test

ngrx router-store - testing router navigation effects


I have effects and tests working as follow:

LoginRedirect Effect

  @Effect()
  public loginSuccess$: Observable<Action> = this.actions$.pipe(
    ofType<LoginSuccess>(AuthActionTypes.LoginSuccess),
    map( action => action.payload ),
    concatMap( (payload: Client) => [
      new SecondAction(payload),
    ]),
    tap(() => this.router.navigate(['/somepage']))
  );

LoginRedirect Effect Test

  describe('#loginSuccess$', () => {
    it('should trigger SecondAction action and redirect to somepage', () => {
      spyOn(effects['router'], 'navigate');

      actions = hot('-a-', { a: new LoginSuccess({} as any)});
      expected = cold('-b', { b: new SecondAction({} as any)});

      expect(effects.loginSuccess$).toBeObservable(expected);
      expect(effects['router'].navigate).toHaveBeenCalled();
    });
  });

Tests are passing as expected. I am trying to write the same tests for an Observable of an action that happens on the ngrx router-store. Example, here is my Effect.

clearError Effect

  @Effect()
  public clearError$: Observable<Action> = this.actions$.pipe(
    ofType(ROUTER_NAVIGATION), // <-- not using the conventional 
    mapTo(new ClearErrorMessage())
  );

clearError EffectTest

  describe('#clearError$', () => {
    it('should trigger ClearErrorMessage action', () => {
      spyOn(effects['actions$'], 'pipe').and.returnValue(hot('-a', { a: ROUTER_NAVIGATION }));

      expected = cold('-b', { b: new ClearErrorMessage() });

      expect(effects.clearError$).toBeObservable(expected);
    });
  });

However, here I am getting an error:

Expected $.length = 0 to equal 1.
Expected $[0] = undefined to equal Object({ frame: 10, notification: Notification({ kind: 'N', value: ClearErrorMessage({ type: '[Auth] ClearErrorMessage' }), error: undefined, hasValue: true }) }).

Any pointers would be much appreciated


Solution

  • You should also use actions just like you did in your first example instead of spyOn(...)

    Also ROUTER_NAVIGATION is just a string, you'll have to create an action.

    describe('#clearError$', () => {
       actions$ = hot('-a---', { a: {type: ROUTER_NAVIGATION} });   
       expected = cold('-b', { b: new ClearErrorMessage() });
       expect(effects.clearError$).toBeObservable(expected);
    });