mercredi 1 avril 2020

How to jest-test a redux-thunk action with two dispatches inside?

I'm using react and redux-thunk.

I have this action here, to fetch documents from API (I need the dispatch to call it so I wouldn't like to remove it) and then save the docs on my store with a second dispatch:

export function searchDocuments(search) {
    return async (dispatch, getState) => {
        const { loggedUser } = getState().userReducer;

        let documents = [];

        if (search.length > 1) {
            documents = await dispatch(apiSearchFiles(search, loggedUser));
        }

        return dispatch({
            type: UPDATE_SEARCH_DOCUMENTS,
            payload: documents,
        });
    };
}

And I'm trying test it with:

describe('Call searchDocuments correctly', () => {
    it('should call the correct type on searchDocuments dispatch', async () => {
        const store = mockStore({
            userReducer: { loggedUser: { name: 'user1' } },
            documentsResults: [],
        });
        const payload = [{ name: 'doc1' }];
        const expectedActions = [{ type: UPDATE_SEARCH_DOCUMENTS, payload }];

        return store.dispatch(searchDocuments('searchTerm')).then(() => {
            expect(store.getActions()).toEqual(expectedActions);
        });
    });
});

But I always got this error, pointing to this line: Error:

Actions must be plain objects. Use custom middleware for async actions

Line:

documents = await dispatch(gDriveSearchFiles(search, loggedUser));

I tried to follow the approach from this similar question but it didn't work for me, his action is a little different.

So I would like to know if there is any way to handle that first dispatch inside of my action.

Aucun commentaire:

Enregistrer un commentaire