retry NPM package with global fetch.
https://www.npmjs.com/package/fetch-retry
使用方式:
const fetch = require('fetch-retry')(global.fetch)
对于我的单元测试,套件显示fetch must be a function
失败。但是,如果我删除取-重试包,我的测试工作。fetch -retry封装全局取回。不管怎样,模拟/测试这个?
我的单元测试是这样的,正如你看到的,它没有fetch-retry
import React from 'react';
import { render, screen } from '@testing-library/react';
import Test from "./Test";
describe("Test", () => {
let originalFetch;
beforeEach(() => {
originalFetch = global.fetch;
global.fetch = jest.fn(() => Promise.resolve({
json: () => Promise.resolve({
value: "Testing something!"
})
}));
});
afterEach(() => {
global.fetch = originalFetch;
});
it('Should have proper description after data fetch', async () => {
// need to put mock logic here to make it work
render(<Test />);
const description = await screen.findByTestId('description');
expect(description.textContent).toBe("Testing something!");
});
});
您可以应用此修复。
创建文件getFetch.ts
:
import getFetchWithRetry from 'fetch-retry';
export const getFetch = () => {
if (process.env.NODE_ENV === 'test') {
return {
fetch: () =>
Promise.resolve({
ok: true,
statusText: 'OK',
json: () => Promise.resolve({}),
}),
};
}
return {
fetch: getFetchWithRetry(global.fetch),
};
};
然后像这样使用:
const { fetch } = getFetch();
fetch(…)