How to use fetch-mock-jest with Typescript?
Opened this issue · 1 comments
flixman commented
I am having serious trouble making fetch-mock-jest work within my typescript project. Maybe somebody can point me to what I am doing wrong?
After the imports I have the following:
import type { FetchMockStatic } from 'fetch-mock';
import fetch from 'node-fetch';
import 'fetch-mock-jest';
jest.mock('node-fetch', () => {
return require('fetch-mock-jest').sandbox();
});
const fetchMock = fetch as unknown as FetchMockStatic;
When running the tests I am getting the following error: "TypeError: require(...).sandbox is not a function". What am I doing wrong?
julienw commented
I used this in a project:
// The import of fetchMock also installs jest matchers as a side effect.
import fetchMock from 'fetch-mock-jest';
beforeEach(function () {
// Install fetch and fetch-related objects globally.
// Using the sandbox ensures that parallel tests run properly.
globalThis.fetch = fetchMock.sandbox() as (
input: RequestInfo | URL,
init?: RequestInit,
) => Promise<Response>;
});
afterEach(() => {
fetchMock.mockReset();
});
Then in tests:
import type { FetchMockSandbox } from 'fetch-mock';
(global.fetch as FetchMockSandbox)
.get('begin:XXX', body)
.catch(404);
This isn't perfect (especially that FetchMockSandbox
doesn't have the newer methods such as any()
) but this works quite fine for me.