Josh Hale
Josh Hale

Reputation: 467

redux-mock-store store's state is not updating after dispatching actions

I have a logger middleware that shows actions about to be dispatched and next state.

I am writing tests for my action and in the mock store I am dispatching the actions. These successfully dispatch however the mock store state is not being updated (as shown by the aforementioned logger).

please note I am using redux-mock-store.

//authActionTest.js

it('creates LOGIN_SUCCESS when successful login has occured', ()=>{

//array of expected actions to be dispatched.
const expectedActions = [
  { type: constants.LOGIN_REQUEST },
  { type: 'LOGIN_SUCCESS',
            payload: {
                uid: '123abc',
                role: 'clinician'
    }}
]
const store = mockStore({ auth : {} })

return store.dispatch(actions.loginUser('[email protected]', 'password123'))
expect(store.getActions()).toEqual(expectedActions)
})

The logger shows the following:

//logger
dispatching({ type: 'LOGIN_REQUEST })
next state { auth: {} }
dispatching({ type: 'LOGIN_SUCCESS',
   payload: { uid: 123,
              role: 'clinician'
          })
next state { auth: {} }

Upvotes: 2

Views: 2353

Answers (1)

anoop
anoop

Reputation: 3297

You are trying to test an async action.

So to answer this question, we can follow what the redux docs are suggesting.

  describe('async actions', () => {
    afterEach(() => {
      nock.cleanAll();
    });
    it('creates LOGIN_SUCCESS on successful login', () => {
      nock('http://example.com/')
        .get('/login')
        .reply(200, payload: { uid: 123, role: 'clinician' });

      const expectedActions = [
        { type: types.LOGIN_REQUEST },
        { type: types.LOGIN_SUCCESS, payload: { uid: 123, role: 'clinician' } },
      ];
      const store = mockStore({ auth: {} });

      return store.dispatch(actions.loginUser())
        .then(() => { // return of async actions
          expect(store.getActions()).toEqual(expectedActions);
        });
    });
  });

You may need to do some modifications to the above code to make it working.

If you are using axios, I would suggest to use moxios package instead of nock.

Upvotes: 0

Related Questions