2017-02-16 82 views
0

我一直有問題使用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'); 
    }); 
}); 

回答

0

似乎有一些問題與使用箭扣測試由愛可信提出了要求。有一個issue in nock's repository討論。

我發現@supnate對這個問題的評論解決了我的問題。此外,我在我的代碼中致電nock.cleanAll();beforeEach()構造是主要罪魁禍首的問題。

解決方法是刪除它。不要使用nock.cleanAll()!所以,現在一切正常,以測試由axios發出的請求:

import axios from 'axios'; 
import httpAdapter from 'axios/lib/adapters/http'; 

axios.defaults.host = SOMEWHERE; // e.g. http://www.somewhere.com 
axios.defaults.adapter = httpAdapter; 

describe('Your Test',() => { 
    test('should do something',() => { 
    nock(SOMEWHERE) 
     .get('/some/thing/3') 
     .reply(200, { some: 'thing', bla: 123 }); 

    // then test your stuff here 
); 
}); 
0

據我所知,nock npm模塊只能在Node中工作,而不能在瀏覽器中工作。您是在測試套件中使用nock還是在開發時作爲API的補充?如果是後者,我認爲nock中間件不會起作用。當你連接到互聯網時,你可能看到了真實API的反應,而不是模擬API,而且nock不會攔截任何東西。

如果您想嘗試類似的適配器,無論是在節點,在瀏覽器的工作原理,看看axios-mock-adapter

+0

我使用axios在我的動作創建者中進行HTTP調用。爲了測試,我使用Jest並打電話給nock來設置一個攔截器。看起來攔截器根本沒有被使用。當我走出去(或調用nock.disableNetConnect())時,我的axios.get失敗並進入其catch塊。 – nbkhope

+0

你可以編輯你的問題,讓它有你的測試用例嗎? –

相關問題