fetch-mock-jest and jest-fetch-mock are both npm packages designed to help developers mock the global fetch API in Jest test environments. They enable reliable, isolated testing of code that makes HTTP requests by replacing the real fetch with a controllable mock implementation. This is essential for writing fast, deterministic unit and integration tests without hitting external APIs.
When testing frontend code that uses fetch, you need a reliable way to intercept HTTP calls without making real network requests. Both fetch-mock-jest and jest-fetch-mock solve this problem, but they take different approaches under the hood. Let’s compare how they work in practice.
fetch-mock-jest is a thin integration layer on top of fetch-mock, a powerful standalone mocking library. It doesn’t reimplement mocking logic — it configures fetch-mock to play nicely with Jest’s test lifecycle.
// fetch-mock-jest example
import { enableFetchMocks } from 'fetch-mock-jest';
enableFetchMocks();
beforeEach(() => {
fetchMock.resetMocks();
});
it('calls the API', async () => {
fetchMock.getOnce('https://api.example.com/user', { id: 123 });
const user = await getUser();
expect(user.id).toBe(123);
});
jest-fetch-mock replaces global.fetch with a Jest mock function (jest.fn()). This means all the familiar Jest assertion methods work out of the box.
// jest-fetch-mock example
import 'jest-fetch-mock';
fetchMock.enableMocks();
it('calls the API', async () => {
fetchMock.mockResponseOnce(JSON.stringify({ id: 123 }));
const user = await getUser();
expect(user.id).toBe(123);
expect(fetch).toHaveBeenCalledWith('https://api.example.com/user');
});
Both packages require minimal setup, but their cleanup strategies differ slightly.
With fetch-mock-jest, you typically call fetchMock.resetMocks() in beforeEach to clear routes and call history between tests. The package itself handles restoring the original fetch during Jest’s teardown.
// fetch-mock-jest cleanup
import { enableFetchMocks } from 'fetch-mock-jest';
enableFetchMocks();
beforeEach(() => {
fetchMock.resetMocks(); // clears routes and history
});
With jest-fetch-mock, calling fetchMock.enableMocks() replaces global.fetch once. Between tests, you usually call fetchMock.resetMocks() which internally calls fetch.mockReset(), clearing both implementation and call history.
// jest-fetch-mock cleanup
import 'jest-fetch-mock';
fetchMock.enableMocks();
beforeEach(() => {
fetchMock.resetMocks(); // equivalent to fetch.mockReset()
});
fetch-mock-jest inherits fetch-mock’s rich matching system. You can match by exact URL, glob patterns, regular expressions, or even custom functions.
// fetch-mock-jest: advanced matching
fetchMock.get('/api/users/*', { name: 'Alice' }); // glob
fetchMock.post(/\/api\/posts/, { id: 1 }); // regex
fetchMock.get(
(url, opts) => opts.headers?.Authorization,
{ secret: 'data' }
); // custom matcher
jest-fetch-mock matches only by full URL string unless you use Jest’s built-in mock implementations. For pattern matching, you’d need to implement your own logic inside mockImplementation.
// jest-fetch-mock: basic matching
fetchMock.mockResponseOnce(JSON.stringify({ id: 1 }));
// Only matches the next call, regardless of URL
// To match specific URLs, you must check inside mockImplementation
fetchMock.mockImplementation((url) => {
if (url === 'https://api.example.com/user') {
return Promise.resolve({ json: () => ({ id: 123 }) });
}
return Promise.reject(new Error('Unexpected URL'));
});
Both let you return JSON, text, or status codes, but with different syntax.
fetch-mock-jest uses object-based response configuration:
fetchMock.get('https://api.example.com/error', {
status: 404,
body: { error: 'Not found' }
});
jest-fetch-mock provides helper methods like mockResponseOnce and mockRejectOnce:
fetchMock.mockResponseOnce(
JSON.stringify({ error: 'Not found' }),
{ status: 404 }
);
For non-JSON responses, jest-fetch-mock requires manual construction of the Response object or use of mockResponseOnce with raw strings.
Because jest-fetch-mock uses a real Jest spy, you get full access to Jest’s assertion API:
expect(fetch).toHaveBeenCalledTimes(2);
expect(fetch).toHaveBeenCalledWith(
'https://api.example.com/user',
expect.objectContaining({ method: 'GET' })
);
With fetch-mock-jest, you assert through fetchMock’s own API:
expect(fetchMock.called()).toBe(true);
expect(fetchMock.calls()).toHaveLength(2);
expect(fetchMock.lastCall()[0]).toBe('https://api.example.com/user');
If your team is already fluent in Jest matchers, jest-fetch-mock’s approach may feel more natural. If you prefer a dedicated mocking interface, fetch-mock-jest offers more semantic clarity for complex scenarios.
Both support simulating network errors:
// fetch-mock-jest
fetchMock.get('https://api.example.com/fail', 500);
// jest-fetch-mock
fetchMock.mockRejectOnce(new Error('Network error'));
However, fetch-mock-jest can simulate partial failures (e.g., 50% of requests fail) using its route repetition controls, while jest-fetch-mock requires manual sequencing with mockImplementationOnce.
Use fetch-mock-jest when:
Use jest-fetch-mock when:
Neither package is deprecated, and both are actively maintained. The choice boils down to whether you value expressive request matching (fetch-mock-jest) or native Jest integration (jest-fetch-mock). For most greenfield projects with complex API interactions, fetch-mock-jest’s routing power pays off. For simpler apps or teams new to mocking, jest-fetch-mock’s simplicity wins.
Choose fetch-mock-jest if you want a lightweight wrapper around the well-established fetch-mock library that integrates cleanly with Jest’s cleanup lifecycle. It automatically resets mocks after each test using afterEach, reducing boilerplate. This package is ideal when you need advanced routing capabilities (like matching by URL patterns or headers) and prefer a declarative mock setup that closely mirrors production request shapes.
Choose jest-fetch-mock if you prefer a simpler, Jest-native mocking experience that directly extends Jest’s built-in mock functions. It replaces global.fetch with a Jest spy, giving you access to standard Jest matchers like toHaveBeenCalledWith and toHaveBeenCalledTimes. This approach works well for straightforward mocking scenarios where you primarily need to assert call history and return canned responses without complex route logic.
Wrapper around fetch-mock - a comprehensive, isomorphic mock for the fetch api - which provides an interface that is more idiomatic when working in jest.
The example at the bottom of this readme demonstrates the intuitive API, but shows off only a fraction of fetch-mock's functionality. Features include:
fetch-mock-jest requires the following to run:
node-fetch is not included as a dependency of fetch-mock.fetch API either natively or via a polyfill/ponyfillnpm install -D fetch-mock-jest
const fetchMock = require('fetch-mock-jest')
jest.mock('node-fetch', () => require('fetch-mock-jest').sandbox())
const fetchMock = require('node-fetch')
Please refer to the fetch-mock documentation and cheatsheet
All jest methods for configuring mock functions are disabled as fetch-mock's own methods should always be used
All the built in jest function inspection assertions can be used, e.g. expect(fetchMock).toHaveBeenCalledWith('http://example.com').
fetchMock.mock.calls and fetchMock.mock.results are also exposed, giving access to manually inspect the calls.
The following custom jest expectation methods, proxying through to fetch-mock's inspection methods are also available. They can all be prefixed with the .not helper for negative assertions.
expect(fetchMock).toHaveFetched(filter, options)expect(fetchMock).toHaveLastFetched(filter, options)expect(fetchMock).toHaveNthFetched(n, filter, options)expect(fetchMock).toHaveFetchedTimes(n, filter, options)expect(fetchMock).toBeDone(filter)filter and options are the same as those used by fetch-mock's inspection methodsFetched replaced by any of the following verbs to scope to a particular method: + Got + Posted + Put + Deleted + FetchedHead + Patchede.g. expect(fetchMock).toHaveLastPatched(filter, options)
fetchMock.mockClear() can be used to reset the call history
fetchMock.mockReset() can be used to remove all configured mocks
Please report any bugs in resetting mocks on the issues board
const fetchMock = require('fetch-mock-jest');
const userManager = require('../src/user-manager');
test(async () => {
const users = [{ name: 'bob' }];
fetchMock
.get('http://example.com/users', users)
.post('http://example.com/user', (url, options) => {
if (typeof options.body.name === 'string') {
users.push(options.body);
return 202;
}
return 400;
})
.patch(
{
url: 'http://example.com/user'
},
405
);
expect(await userManager.getAll()).toEqual([{ name: 'bob' }]);
expect(fetchMock).toHaveLastFetched('http://example.com/users
get');
await userManager.create({ name: true });
expect(fetchMock).toHaveLastFetched(
{
url: 'http://example.com/user',
body: { name: true }
},
'post'
);
expect(await userManager.getAll()).toEqual([{ name: 'bob' }]);
fetchMock.mockClear();
await userManager.create({ name: 'sarah' });
expect(fetchMock).toHaveLastFetched(
{
url: 'http://example.com/user',
body: { name: 'sarah' }
},
'post'
);
expect(await userManager.getAll()).toEqual([
{ name: 'bob' },
{ name: 'sarah' }
]);
fetchMock.mockReset();
});