0

我正在尝试模拟这个 axios 调用:

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

如果调用成功,应该同时派发动作创建者 fetchCountryPending() 和 fetchCountryFullfilled(country)。当我像这样嘲笑它时:

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

第二个期望失败,console.log(actions) 只显示一个包含一个操作的数组,但它应该包含两个操作,fetchCountryPending 和 fetchCountrySuccess。当我登录('dispatched')时,它显示第二个动作正在终端中调度。

4

2 回答 2

1

您可以尝试使其阻止异步并调度操作吗?我相信在您的获取请求返回值之前测试正在运行

于 2018-12-10T15:20:03.937 回答
0

我无法让 then(() => {}) 块工作,但我能够等待该函数并使其异步:

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