模拟-axios-适配器不模拟获取请求

时间:2018-12-11 10:35:12

标签: reactjs redux redux-mock-store axios-mock-adapter

我正在尝试测试此功能:

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

这是我的考试:

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

运行此测试时,出现错误UnhandledPromiseRejectionWarning,未收到fetchCountryPending,而已收到fetchCountryRejected。似乎onGet()没有执行任何操作。当我注释掉该行时 mock.onGet('/api/v1/countries/?search=${query}').reply(200, country),我最终得到了完全相同的结果,使我相信没有嘲笑。我在做什么错了?

1 个答案:

答案 0 :(得分:0)

我无法使.then(()=> {})正常工作,因此我将该函数转换为异步函数并等待分派:

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