fetch-mock-jest vs jest-fetch-mock
Mocking fetch() in Jest Tests for Frontend Applications
fetch-mock-jestjest-fetch-mock

Mocking fetch() in Jest Tests for Frontend Applications

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.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
fetch-mock-jest95,08260-175 years agoMIT
jest-fetch-mock0893-866 years agoMIT

Mocking fetch() in Jest: fetch-mock-jest vs jest-fetch-mock

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.

🔌 Core Architecture: Wrapper vs Native Jest Spy

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');
});

🧪 Setup and Cleanup

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()
});

🎯 Matching Requests: Pattern-Based vs Full URL

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'));
});

📤 Response Configuration

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.

🔍 Assertion Capabilities

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.

⚠️ Error Handling and Edge Cases

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.

🔄 Real-World Recommendation

  • Use fetch-mock-jest when:

    • You need to mock many endpoints with different behaviors
    • Your app uses dynamic URLs (query params, path variables)
    • You want declarative, readable mock definitions that mirror real API contracts
  • Use jest-fetch-mock when:

    • Most tests only mock one or two simple endpoints
    • Your team prefers using standard Jest assertions everywhere
    • You’re already deep in the Jest ecosystem and want minimal conceptual overhead

💡 Final Thought

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.

How to Choose: fetch-mock-jest vs jest-fetch-mock

  • fetch-mock-jest:

    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.

  • jest-fetch-mock:

    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.

README for fetch-mock-jest

fetch-mock-jest

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:

  • mocks most of the fetch API spec, even advanced behaviours such as streaming and aborting
  • declarative matching for most aspects of a http request, including url, headers, body and query parameters
  • shorthands for the most commonly used features, such as matching a http method or matching one fetch only
  • support for delaying responses, or using your own async functions to define custom race conditions
  • can be used as a spy to observe real network requests
  • isomorphic, and supports either a global fetch instance or a locally required instanceg

Requirements

fetch-mock-jest requires the following to run:

  • Node.js 8+ for full feature operation
  • Node.js 0.12+ with limitations
  • npm (normally comes with Node.js)
  • jest 25+ (may work with earlier versions, but untested)
  • Either
    • node-fetch when testing in Node.js. To allow users a choice over which version to use, node-fetch is not included as a dependency of fetch-mock.
    • A browser that supports the fetch API either natively or via a polyfill/ponyfill

Installation

npm install -D fetch-mock-jest

global fetch

const fetchMock = require('fetch-mock-jest')

node-fetch

jest.mock('node-fetch', () => require('fetch-mock-jest').sandbox())
const fetchMock = require('node-fetch')

API

Setting up mocks

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

Inspecting mocks

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)

Notes

  • filter and options are the same as those used by fetch-mock's inspection methods
  • The obove methods can have Fetched replaced by any of the following verbs to scope to a particular method: + Got + Posted + Put + Deleted + FetchedHead + Patched

e.g. expect(fetchMock).toHaveLastPatched(filter, options)

Tearing down mocks

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

Example

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();
});