Search code examples
unit-testingreduxjestjsredux-thunk

How can I test Thunk actions with Jest?


I'm new to unit testing Redux-Thunk async actions using Jest.

Here is my code:

export const functionA = (a, b) => (dispatch) => {
    dispatch({ type: CONSTANT_A, payload: a });
    dispatch({ type: CONSTANT_B, payload: b });
} 

How can I test this function using Jest?


Solution

  • You have an example in the Redux docs: http://redux.js.org/docs/recipes/WritingTests.html#async-action-creators

    import configureMockStore from 'redux-mock-store'
    import thunk from 'redux-thunk'
    
    const middlewares = [thunk]
    const mockStore = configureMockStore(middlewares)
    
    describe('async actions', () => {
        
      it('should dispatch actions of ConstantA and ConstantB', () => {
        const expectedActions = [
          {type: 'CONSTANT_A', payload: 'a'},
          {type: 'CONSTANT_B', payload: 'b'} 
        ]
    
        const store = mockStore({ yourInitialState })
        store.dispatch(functionA('a', 'b'))
    
        expect(store.getActions()).toEqual(expectedActions)
      })
    })