我在测试以下异步Redux操作时遇到了问题。
export default function getBestPracticesInfo() {
return function (dispatch, getState) {
axios.get("testurl")
.then(response => {
return dispatch({type: "GET_BEST_PRACTICE", payload: response.data})
}).catch(error => {
return error
})
}
}我想简单地验证该操作是否使用预期的有效负载调度正确的操作。为此,我模拟了axios调用、dispatch和getState()方法。模拟的dispatch()方法返回一个promise,其中包含用于调用它的数据。这样,我就可以确保我的测试断言不会在我的axios承诺解析之前触发。然而,在我的测试中,action(dispatch, getState)返回的是undefined,这让我困惑不解。我期待它返回一个承诺。
describe('metaDataActions tests', () => {
let mock;
beforeEach(() => {
mock = new MockAdapter(axios);
mock.onGet('testurl').reply(200, {data: 'TEST BEST PRACTICE RESPONSE'});
sessionStorage.clear();
});
it('should call getBestPracticesInfo', () => {
const getState = ()=> {return {metaData: {meta: {api: {bestPractices: '/api/v1/best_practices'}}}}};
const dispatch = jest.fn(info => {
return new Promise(resolve => {
resolve(info);
})
});
const action = getBestPracticesInfo();
action(dispatch, getState).then(res =>
expect(res).toEqual({type: "GET_BEST_PRACTICES_INFO", payload: response.data})
);
});
});发布于 2019-07-03 21:42:03
在操作代码中,必须使用return语句来返回axios promise的结果。
export default function getBestPracticesInfo() {
return function (dispatch, getState) {
return axios.get("testurl")
.then(response => {
return dispatch({type: "GET_BEST_PRACTICE", payload: response.data})
}).catch(error => {
return error
})
}
}https://stackoverflow.com/questions/56842791
复制相似问题