我一直有問題使用nock來測試我的Redux動作創作者。當我離線時,我不斷收到失敗的承諾,這意味着使用Axios的HTTP請求不成功。當我上網時,它可以工作,但是。只有在有互聯網連接的情況下nock才能工作嗎?
那麼nock只有在有互聯網連接時才能工作?
行動造物主(使用愛可信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
});
});
};
};
玩笑測試行動的創建者(箭扣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');
});
});
我使用axios在我的動作創建者中進行HTTP調用。爲了測試,我使用Jest並打電話給nock來設置一個攔截器。看起來攔截器根本沒有被使用。當我走出去(或調用nock.disableNetConnect())時,我的axios.get失敗並進入其catch塊。 – nbkhope
你可以編輯你的問題,讓它有你的測試用例嗎? –