1

我正在尝试测试此功能:

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)时,我最终得到了完全相同的结果,让我相信没有任何东西被嘲笑。我究竟做错了什么?

4

1 回答 1

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))
  });
于 2019-03-28T17:54:37.033 回答