A lightweight library for mocking fetch requests in Jest and Vitest test environments. Version 3.1.2 is current. It provides a global fetchMock object with methods like mockResponseOnce, mockResponses, and mockReject to simulate different HTTP responses and errors. Works with cross-fetch polyfill, supports TypeScript, and is compatible with both Node.js and browser-like runtimes. Compared to alternatives like nock, it integrates directly with Jest's mocking system, offering a simpler API for common use cases. Note: This is a fork of the original jest-fetch-mock, which is unmaintained and not published to npm with latest fixes.
npm install jest-fetch-mock-forkNo compatibility data collected yet for this library.
Verified import paths — ran on the pinned version, not inferred.
Demonstrates basic setup with enableMocks, then a test for a successful fetch and one for a rejected fetch using mockResponseOnce and mockRejectOnce.
Set 'resetMocks: false' in Jest config if using setupJest.js with enableMocks(), or move enableMocks() to a beforeEach block.
Update test code to use the new API: mockResponseOnce(body, init) where init is an object with status, headers, etc.
Always pass body and init as pairs. Use fetchMock.mockResponses([body1, init1], [body2, init2], ...) or pass multiple pairs.
Use fetchMock.mockIf(/pattern/, handler) to scope mocks to specific URLs, or call fetchMock.doMock() to enable global mocking explicitly.
Ensure enableMocks() is called in setup file before tests, and use const { fetchMock } = require('jest-fetch-mock-fork') if needed.Add "resetMocks": false to Jest configuration in package.json, or move enableMocks() to a beforeEach() in each test file.
Use the global fetchMock variable (after enableMocks()) or import/require as CommonJS: const { fetchMock } = require('jest-fetch-mock-fork')