Search code examples
angularjasminengrx

Testing ngrx meta reducers


I have a meta reducer that should clear the state when logging out.

export function clearState(reducer: ActionReducer<any>): ActionReducer<any> {
  return (state, action) => {
    if (action.type === AuthActionTypes.UNAUTHENTICATED) {
      state = undefined;
    }
    return reducer(state, action);
  };
}

export const metaReducers: MetaReducer<any>[] = [clearState];

I want to unit test this piece of code. I have tested normal reducers before but for me it is hard to apply the same technique when writing a test for the meta reducer. And there are no examples in the docs.


Solution

  • I figured out a way to test it after digging deep in the ngrx source code

    const invokeActionReducer = (currentState, action: any) => {
      return clearState((state) => state)(currentState, action);
    };
    
    it('should set state to initial value when logout action is dispatched', () => {
      const currentState = { /* state here */ };
    
      expect(invokeActionReducer(currentState, userUnauthenticated)).toBeFalsy();
    });
    

    Source