Search code examples
reactjsreduxredux-mock-storeaxios-mock-adapter

Mock-axios-adapter not mocking get request


I'm trying to test this function:

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

Here is my test:

describe('country async actions', () => {
  let store;
  let mock;

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

  afterEach(() => {
    mock.restore();
    store.clearActions();
  });

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

When I run this test, I get an error UnhandledPromiseRejectionWarning and that fetchCountryPending was not received and that fetchCountryRejected was. It seems as if onGet() is not doing anything. When I comment out the line mock.onGet('/api/v1/countries/?search=${query}').reply(200, country), I end up getting the exact same result, making me believe that nothing is being mocked. What am I doing wrong?


Solution

  • I couldn't get the .then(() => {}) to work, so I turned the function into an async function and awaited the dispatch:

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