reactjsreduxredux-mock-store

Redux mock store only returning one action when multiple actions are dispatched


I'm trying to mock this axios call:

export const fetchCountry = (query) => {
  return dispatch => {
    dispatch(fetchCountryPending());
    return axios.get(`${process.env.REACT_APP_API_URL}/api/v1/countries/?search=${query}`)
      .then(response => {
        const country = response.data;
        dispatch(fetchCountryFulfilled(country));
      })
      .catch(err => {
        dispatch(fetchCountryRejected());
        dispatch({type: "ADD_ERROR", error: err});
      })
  }
}

Which on a successful call, should dispatch both action creators fetchCountryPending() and fetchCountryFullfilled(country). When I mock it like so:

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

// Async action tests
describe('country async actions', () => {
  let store;
  let mock;

  beforeEach(function () {
    mock = new MockAdapter(axios)
    store = mockStore({ country: [], fetching: false, fetched: true })
  });

  afterEach(function () {
    mock.restore();
    store.clearActions();
  });

  it('dispatches FETCH_COUNTRY_FULFILLED after axios request', () => {
    const query = 'Aland Islands'
    mock.onGet(`${process.env.REACT_APP_API_URL}/api/v1/countries/?search=${query}`).replyOnce(200, country)
    store.dispatch(countryActions.fetchCountry(query))
    const actions = store.getActions()
    console.log(actions)
    expect(actions[0]).toEqual(countryActions.fetchCountryPending())
    expect(actions[1]).toEqual(countryActions.fetchCountryFulfilled(country))
  });
});

The second expect fails and console.log(actions) only shows an array with the one action, but it should contain both actions, fetchCountryPending and fetchCountrySuccess. When I log ('dispatched'), it shows the second action is getting dispatched in the terminal.


Solution

  • I couldn't get a then(() => {}) block to work but I was able to await the function and make it async:

      it('dispatches FETCH_COUNTRY_FULFILLED after axios request', async () => {
        const query = 'Aland Islands'
        mock.onGet(`${process.env.REACT_APP_API_URL}/api/v1/countries/?search=${query}`).replyOnce(200, country)
        await store.dispatch(countryActions.fetchCountry(query))
        const actions = store.getActions()
        console.log(actions)
        expect(actions[0]).toEqual(countryActions.fetchCountryPending())
        expect(actions[1]).toEqual(countryActions.fetchCountryFulfilled(country))
      });
    });