1
votes

I am trying to test my mapDispatchToProps actions when an async function is dispatched. I almost tried every possible solution I found and nothing worked so far. I'm always getting the same error:

I'm getting this error: TypeError: store.dispatch(...).then is not a function

I tried the solution included in redux-mock-store https://github.com/dmitry-zaets/redux-mock-store. I included my middlewares to my mockStore, but it didn't fix the issue.

I tried the solution proposed by Michael Peyper here Testing dispatched actions in Redux thunk with Jest.

We created a function to build the mockStore so I tried to create my mockStore directly within my test file instead, but they both returned the same error.

I can't put all the solutions I tried here because it would take me weeks, but it gives you an idea.

Here's the code for my test:

describe('Component async actions', () => {
        const middlewares = [thunk, queryMiddleware];
        const createMockStore = configureStore(middlewares);
        const store = createMockStore();

        afterEach(() => {
            jest.clearAllMocks();
        });

        const someData = {};

        const expectedActions = { 
            type: ADD_DATA,
            payload: someData
        };

        it('should handle addData', () => {
            return store.dispatch(actions.addData(someData)).then(() => {
                expect(store.getActions()[0]).toEqual(expectedAction);
            });
        });
 });

Here's my mapDispatchToProps:

function mapDispatchToProps(dispatch) {
    return {
        addData: data => dispatch(addData(data))
            .then(({ status }) => {
                dispatch(showNotification({ status }));
            }),
    };
};

I would like to at least be able to get to the expect part and fix this if there's any error in my test, but I can't get passed the dispatch().then

Again, here's the error I get each time: TypeError: store.dispatch(...).then is not a function

Thanks in advance!

1
Does actions.addData return a Promise?Brian Adams
@brian-lives-outdoors Yes it doesnisois
@brian-lives-outdoors You seem to have a lot of experience with testing async dispatch with jest and enzyme. My solution works but it doesn't enter the .then part. I'm wondering if there's a better way to do this so I can also test the 'showNotification' part.nisois

1 Answers

0
votes

I don't know if anyone will get this problem, but I found a solution.

First of all, I had to add my thunk middleware to my createStore from redux-mock-store.

import thunk from 'redux-thunk';

...

const createMockStore = createStore([thunk]);

Then I did a mock of my addData function like this:

import { addData } from 'path/to/addData';

...

jest.mock('path/to/addData');

and I added this code within my test:

addData.mockReturnValue(() =>
        new Promise((resolve) => resolve({ status: 200 }));
        ));

It works!