我在使用nock测试我的 Redux 动作创建者时遇到了问题。当我离线时,我不断收到失败的承诺,这意味着使用 Axios 的 HTTP 请求不成功。但是,当我上网时,它可以工作。
那么 nock 只有在有 Internet 连接的情况下才有效吗?
Action Creator(使用 axios 0.15.3)
export const fetchSomething = (id) => {
return dispatch => {
dispatch({
type: FETCH_SOMETHING_LOADING
});
return axios.get(`${SOMEWHERE}/something?id=${id}`)
.then(response => {
return dispatch({
type: FETCH_SOMETHING_SUCCESS,
payload: response.data
});
})
.catch(error => {
return dispatch({
type: FETCH_SOMETHING_FAILURE
});
});
};
};
动作创建者的笑话测试(nock v9.0.2)
test('should dispatch success action type if data is fetched successfully', () => {
// Need this in order for axios to work with nock
axios.defaults.adapter = require('axios/lib/adapters/http');
nock(SOMEWHERE)
.get('/something?id=123')
.reply(200, someFakeObject);
thunk = fetchSomething(123);
return thunk(dispatch)
.then(() => {
expect(dispatch.mock.calls[1][0].type).toBe('FETCH_SOMETHING_SUCCESS');
});
});