我在使用并发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操作。我做错了什么?
发布于 2021-01-11 04:25:30
回答可能晚了,但我在寻找类似的答案时在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)
})https://stackoverflow.com/questions/58267165
复制相似问题