peter
peter

Reputation: 1572

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.

Upvotes: 0

Views: 1480

Answers (2)

peter
peter

Reputation: 1572

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))
  });
});

Upvotes: 0

balzee
balzee

Reputation: 56

Can you try making your it block async and dispatch the action. I believe the tests are running before your get requests return the value

Upvotes: 1

Related Questions