[英]Spy on Jest mock
我正在嘗試對 jest.mock 進行間諜活動,(我不是 unmock 你想要的東西的忠實粉絲,我更喜歡“老派”的方式)
這樣我就有了以下測試:
jest.mock('node-fetch');
// ...
it('should have called the fetch function wih the good const parameter and slug', done => {
const slug = 'slug';
const stubDispatch = () => null;
const dispatcher = fetchRemote(slug);
dispatcher(stubDispatch).then(() => {
expect(???).toBeCalledWith(Constants + slug);
done();
});
});
這是我要測試的代碼(不完整,測試驅動):
export const fetchRemote = slug => {
return dispatch => {
dispatch(loading());
return fetch(Constants.URL + slug)
};
};
我的 fetch 模擬實現(實際上是 node-fetch)是:
export default () => Promise.resolve({json: () => []});
模擬效果很好,它很好地取代了通常的實現。
我的主要問題是,我怎樣才能監視那個被嘲笑的 function? 我需要測試它是否已使用良好的參數調用,我絕對不知道如何做到這一點。 在測試實現中有一個“???” 而且我不知道如何創建有關間諜。
任何想法?
在你的模擬實現中,你可以做
const fetch = jest.fn(() => Promise.resolve({json: () => []}));
module.exports = fetch;
現在在你的測試中你需要做
const fetchMock = require('node-fetch'); // this will get your mock implementation not the actual one
...
...
expect(fetchMock).toBeCalledWith(Constants + slug);
希望這可以幫助
對於仍在搜索與內聯模擬一起使用的任何人的現代方法就是:
const fetchSpy = jest.spyOn("node-fetch", "fetch")
...
expect(fetchSpy).toHaveBeenCalledWith(...)
這樣您就不必創建單獨的模擬實現
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.