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.....
}
}
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.According to the documentation:
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.