我正在创建一个 Jest 的测试,以测试是否记录了针对superFetch函数的错误处理的指标。我的方法是为retryFetch创建一个模拟函数并返回Promise拒绝事件。我希望这能赶上superFetch的陷阱,但随后它会一直以superFetch结尾。我该如何处理superFetch catch中的错误?
这些是功能:
// file: fetches.js
export function retryFetch(url) {
return new Promise((resolve, reject) => {
fetch(url).then(response => {
if (response.ok) {
resolve(response);
return;
}
throw new Error();
}).catch(error => {
createSomething(error).then(createSomething => {
reject(createSomething);
});
return;
});
});
});
export function superFetch(url, name, page) {
return retryFetch(url)
.then(response => {
return response;
}).catch(error => {
Metrics.logErrorMetric(name, page);
throw error;
});
}
我的 Jest 测试:
import * as fetch from '../../src/utils/fetches';
describe('Fetch fails', () => {
beforeEach(() => {
fetch.retryFetch = jest.fn(() => Promise.reject(new Error('Error')));
});
it('error metric is logged', () => {
return fetch.superFetch('url', 'metric', 'page').then(data => {
expect(data).toEqual(null);
// received data is {"ok": true};
// why is it even going here? im expecting it to go skip this and go to catch
}).catch(error => {
// this is completely skipped. but I'm expecting this to catch an error
// received error is null, metric was not called
expect(Metrics.logErrorMetric).toHaveBeenCalled();
expect(error).toEqual('Error');
});
});
});
最佳答案
问题是您覆盖了导出模块中的函数,但是superFetch
使用了模块内部的原始函数,因此覆盖将无效。
您可以像这样直接模拟fetch
:
global.fetch = jest.mock(()=> Promise.reject())