wheresrhys / fetch-mock-jest

Jest wrapper for fetch-mock, a comprehensive stub for fetch
http://www.wheresrhys.co.uk/fetch-mock/
MIT License
60 stars 11 forks source link

How to use fetch-mock-jest with Typescript? #62

Open flixman opened 11 months ago

flixman commented 11 months ago

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 8 months ago

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.