Search code examples
reduxjasminengrx

testing ngrx: dispach action and expect the store


Is it possible to dispatch an action inside the test and expect the store , without test effects, reducers, selectors? I really can't find a good example, so I am wondering which is the best practice to test ngrx.

Any idea?


Solution

  • The "store" is a term to represent your entire NgRx system. The reducer is what produces state. I think you want to test how your actions produce state. To do this, you need to focus on your "state creator" which is you reducer

    A reducer is a function. Consider this simple example where I activate a "product" I want to test that when an ActivateProduct action appears, that my loading state is set to true

    export function productActivationReducer(state = initialState, action: ProductActivationActions): ProductActivationState {
      switch (action.type) {
        case ProductActivationActionTypes.ActivateProductSuccess:
          return {
            isLoading: true,
            error: null,
            data: action.payload,
          };
    
        default:
          return state;
      }
    }
    

    Your reducer is a function. The function can be invoked with I would create a test that would invoke the function and test what state is returned.

    import { productActivationReducer, initialState } from './product-activation.reducer';
    
      describe('ActivateProductSuccess', () => {
        it('should set the next state', () => {
          action = new ActivateProductSuccess({ foo: 'bar'});
          result = productActivationReducer(initialState, action);
          expect(result.data).toEqual({ foo: 'bar'});
          expect(result.error).toBeNull();
          expect(result.loading).toBe(true);
        });
      });