Search code examples
reactjsreduxredux-thunk

How to write an integration test of an action with a reducer in react-redux-thunk


I have a function in utils.fetch_json that returns a promise of a json (or some error in json). I want to test that, when an action that uses fetch_json is dispatched, updateData here, the store state is updated with the payload of the json when the API's json is valid.

Case in point:

import {createStore,  applyMiddleware} from "redux";
import Store from "../../reducers/foobar";
import { updateData } from "../../actions/foobar";
import utils from '../../utils'
import thunk from 'redux-thunk';

const data = {
    a: ["A1", "A2"],
    b: [20, 10],
}

describe("Test the reducer-actions", () => {
    utils.fetch_json = jest.fn().mockResolvedValue(data);

    it("updates the state when updateData is dispatched", () => {
        const store = createStore(Store, applyMiddleware(thunk));
        store.dispatch(updateData())
        expect(store.getState().data).toEqual(data);
    });
});

this fails because the execution of store.dispatch(updateData()) is async and thus the expect is executed before it, causing the initial state, not data, to be in the store.

I am trying to avoid a dependency for this, but I am willing to use one if the notation is similar to jest.

Note that I am not trying to:

  1. test the reducer in isolation
  2. test the action creator in isolation
  3. test a thunk-action in isolation

I am interested in testing them in integration.


Solution

  • If updateData returns then you can do:

    store.dispatch(updateData()).then(()=>test here)
    

    That is assuming that updateData returns a promise.