1

我在使用并发 API 调用测试函数时遇到问题。这是我要测试的依赖于 redux-thunk 的代码:

const loadResources = () => {
  return (dispatch) => {
    dispatch(setLoaderState(true))
    // events
    API.get('/internal/timeo/api/v0/actions')
      .then(response => initialFetchEventsSuccess(dispatch, response))
      .catch(error => onRequestErrorCallback(dispatch, error));
    // clients
    API.get('/internal/obeya/api/v0/clients')
      .then(response => initialFetchClientsSuccess(dispatch, response))
      .catch(error => onRequestErrorCallback(dispatch, error));
    // resources
    API.get('/internal/obeya/api/v0/resources')
        .then(response => getRessourcesSuccess(dispatch, response))
        .catch(error => onRequestErrorCallback(dispatch, error));
  }
}

// on successfull fetch we dispatch data to the store
const initialFetchEventsSuccess = (dispatch, data) => {
  dispatch(setLoaderState(false))
  dispatch(setErrorState(false))
  dispatch({
    type: LOAD_EVENTS,
    payload: data.data
  });
}

// on successfull fetch we dispatch data to the store
const initialFetchClientsSuccess = (dispatch, data) => {
  dispatch(setLoaderState(false))
  dispatch(setErrorState(false))
  dispatch({
    type: LOAD_CLIENTS,
    payload: data.data
  })
}

// on successfull fetch we dispatch data to the store
const getRessourcesSuccess = (dispatch, data) => {
  dispatch({
    type: SET_RESOURCES,
    payload: data.data
  })
}

它向 API 发送并发请求,然后在成功时将操作分派到 redux 存储。这些请求是独立的,所以我真的不在乎哪个先执行。

但是,当我尝试使用 moxios 和 redux-mock-store 测试此代码时,我只能从我的模拟商店中的第一个请求中分派操作:

it('loadsResources', async (done)=> {
    moxios.stubRequest('/internal/timeo/api/v0/actions', {
      status: 200,
      response: getActionsMock
    });
    moxios.stubRequest('/internal/timeo/api/v0/clients', {
      status: 200,
      response: getClientsMock
    });
    moxios.stubRequest('/internal/timeo/api/v0/resources', {
      status: 200,
      response: getResourcesMock
    });

  const expectedActions = [
     { type: LOAD_EVENTS, payload: getActionsMock},
     { type: LOAD_CLIENTS, payload: getClientsMock},
     { type: SET_RESOURCES, payload: getResourcesMock},
  ]
  const store = makeMockStore({});


  await store.dispatch(loadResources);

  setTimeout(() => {
    const actions = store.getActions();
    console.log(actions)
    done();
  }, 1000);
});

在动作中,无论我设置什么超时,最后我都只会得到 LOAD_EVENTS 动作。我究竟做错了什么 ?

4

1 回答 1

1

也许迟到了,但我在寻找类似答案时在 moxios repo 中遇到了这个问题。

https://github.com/axios/moxios#mocking-a-axioscreate-instance

所以,你是在正确的方向。只需要断言 axios 实例并以这种方式获得结果。

 let axiosInstance;

 beforeEach(() => {
    axiosInstance = axios.create();
    moxios.install(axiosInstance);
 });

 afterEach(() => {
    moxios.uninstall(axiosInstance);
 });

 test('Should get results', (done) => {
    moxios.stubRequest(`url`, {status: 200, response: response /* or response */});
    axiosInstance.get(`url`)
      .then(res => res.status === 200)
      .finally(done)
 })
于 2021-01-10T20:25:30.460 回答