1
votes

I am having trouble testing a thunk using mock-store.

In my thunk I call getState() to get the state of the redux store and then dispatch actions based on the state.

How do I get my thunks getState() call to check the mock stores state and not the redux store state?

    import {initialState} from '../configureStore'
    import {saveAndSendTask} from '../thunks/queueThunk'
    import configureMockStore from 'redux-mock-store'
    import thunk from 'redux-thunk'
    import * as actions from '../actions/index'

    const middlewares = [thunk]
    const mockStore = configureMockStore(middlewares)

    describe('Testing TaskQueue Thunk', () => {
        const store = mockStore(initialState)

        test('Test TaskQueue thunk sends to sever and removes from queue.', () => {
            // removed variables test data for the sake of brevity.

            // Add actions to Mock Store and set up Base state needed to test.
            store.dispatch(actions.addToTaskQueue(task1))
            store.dispatch(actions.addToTaskQueue(task2))
            store.dispatch(actions.setTasks([task1, task2, task3]))
            store.dispatch(actions.selectTask(task3.id))
            store.dispatch(actions.isConnected(true))

            // This is the thunk I want to test.
            store.dispatch(saveAndSendTask())

            expect('something').toEqual('something')
        })
    )}

Here is the thunk I want to test.

    export const saveAndSendTask = (): any => {
      return (dispatch: Dispatch, getState) => {

        // This state is the same as initial state of redux store. Ignores Mock store state.
        console.log(getState())

        // Selected task is undefined.
        dispatch(addToTaskQueue(getState().tasks.selectedTask))

        // ....rest of logic.....
      }
    }
1

1 Answers

4
votes

The redux-mock-store does not update the state but only records the actions passed to the dispatch.

Additionally, the code implementing the getState method in the library either returns the initial state passed or a function.

getState () {
  return isFunction(getState) ? getState(actions) : getState
}

According to the documentation:

Please note that this library is designed to test the action-related logic, not the reducer-related one. In other words, it does not update the Redux store. If you want a complex test combining actions and reducers together, take a look at other libraries (e.g., redux-actions-assertions). Refer to issue #71 for more details.

You can either try another library, follow the recommendation noted in #71 by passing the actions to your reducer manually to get the updated state that you were expecting, or modify your spec to validate the action dispatched in saveAndSendTask using the expected previous state to initialize your mockStore.