Search code examples
jasminengrx

Ngrx unit test jasmine reducer how to compare state


I've done this simple test

// Mocks

    const loginResponseData: LoginResponseDto = {
      auth: { id: 1, username: 'me', roles: [] },
      token: {
        token: 'abc',
        expirationEpochSeconds: 12345
      }
    };
    describe('AuthReducer', () => {
      describe('loginSuccess', () => {
        it('should show loginResponseData state', () => {
          const createAction = loginSuccess({ payload: loginResponseData });

          const result = reducer(initialState, createAction);
          console.log('AUTH', result);
          // How Can I test this?
          //expect(result).toEqual(loginResponseData);
        });
      });
    });
export const initialState: State = {
  error: null,
  loading: false,
  registered: false,
  payload: null
};
const authReducer = createReducer(
  initialState,
  on(AuthActions.loginSuccess, (state, { payload }) => {
    return {
      ...state,
      error: null,
      loading: false,
      payload
    };
  })
);

How I can test result with loginResponseData?


Solution

  • result of a reducer is a new state. You need to share code of your reducer for the right answer. Or to share what console.log outputs.

    Because in your question the code is correct

    describe('AuthReducer', () => {
      describe('loginSuccess', () => {
        it('should show loginResponseData state', () => {
    
          const actionPayload: LoginResponseDto = {
            auth: { id: 1, username: 'me', roles: [] },
            token: {
              token: 'abc',
              expirationEpochSeconds: 12345
            }
          };
    
          // for the test it's fine to have an empty object
          const initialState: any = {
          };
    
          // check what should be changed
          const expectedState = {
            payload: {
              auth: { id: 1, username: 'me', roles: [] },
              token: {
                token: 'abc',
                expirationEpochSeconds: 12345
              },
            },
            error: null,
            loading: false,
          };
    
          const createAction = loginSuccess({ payload: loginResponseData });
    
          // returns updated state we should compare against expected one.
          const actualState = reducer(initialState, createAction);
    
          // assertions
          expect(actualState).toEqual(expectedState);
        });
      });
    });