2017-07-03 68 views
0

我無法找到一個明確的答案,單元測試的正確方法fetch是否在線。我正在使用create-react-app構建。到目前爲止,這是我發現用戶推薦使用的最接近的地方nock & node-fetch。我在這裏看到了一個圖書館的一些發展:https://github.com/wheresrhys/fetch-mock,但它的構建失敗了,這讓我感到緊張。如何使用提取測試API調用

的目標是使這個戲很好地與jest

沒有人有從經驗的最佳途徑的建議使用提取API測試要求?

回答

0

你應該使用像你這樣的fetch-mock鏈接來測試新的fetch API調用。

構建失敗的事實對您來說絕對沒有意義。這只是讓開發人員知道何時向github作出持續發展。當你使用npm i --save-dev fetch-mock時,它會下載(希望)github作者專門發佈的工作發佈版本,而不是失敗的版本。從我的項目的終極版

例咚行動:

import expect from 'expect'; 
import configureStore from 'redux-mock-store'; 
import thunk from 'redux-thunk'; 
import fetchMock from 'fetch-mock'; 

import * as actions from './formActions'; 

const mockStore = configureStore([thunk]); 
const store = mockStore({}); 
const body = { 
    email: '[email protected]', 
}; 

describe('registerFormActions',() => { 
    let calledActions; 

    beforeEach(() => { 
    store.clearActions(); 
    calledActions = store.getActions(); 
    }); 

    afterEach(() => { 
    fetchMock.reset().restore(); 
    }); 

    it('should post form',() => { 
    fetchMock.postOnce('/account/register', body); 

    store.dispatch(actions.submit()).then(() => { 
     expect(fetchMock.called('/account/register')).toBe(true); 
    }); 
    }); 
}); 

export const submit = formData => dispatch => 
fetch('/account/register', { 
    method: 'post', 
    body: formData, 
    credentials: 'same-origin', 
}).then((response) => { 
    if (response.ok) { 
    // Do something cool 
    } 
}); 
+0

嗯,好從別人已經用它,然後聽到。我會繼續向前推進。謝謝,害怕掉下兔子洞。 –

+0

沒問題。下一次我會看看這個文檔,如果它看起來像你需要的那麼沒有理由不使用它,特別是對於不是生產代碼的單元測試。 –

+0

fetch-mock也解決了我的問題。 :) – Ron