Fetch Mocking Library
fetch-mock is a comprehensive library for mocking HTTP requests made using the `fetch` API in JavaScript and TypeScript applications. It is widely used in testing environments to isolate network calls and control their responses. The current stable version is `12.6.0`, with a generally active release cadence, often seeing patch updates multiple times a month to address bug fixes and introduce minor features. Key differentiators include its extensive support for the `fetch` API specification, including advanced behaviors like streaming and aborting requests. It offers declarative matching for various aspects of an HTTP request (URL, headers, body, query parameters), provides convenient shorthands for common scenarios, supports delaying responses, and can function as a spy to observe real network activity. The library is isomorphic, working equally well in Node.js (requiring Node.js 18+ for full feature operation) and modern browser environments, and can be extended with custom matchers.
Common errors
-
Error [ERR_REQUIRE_ESM]: require() of ES Module ... fetch-mock/index.js not supported.
cause Attempting to use `require()` to import `fetch-mock` in a context where it expects an ES module.fixChange `const fetchMock = require('fetch-mock')` to `import fetchMock from 'fetch-mock'`. -
ReferenceError: fetch is not defined
cause Running tests in a Node.js environment older than version 18 without a global `fetch` polyfill or `node-fetch` installed.fixUpgrade Node.js to version 18 or higher, or install `node-fetch` and ensure it's made available globally (e.g., `global.fetch = require('node-fetch')`) before `fetch-mock` is initialized. -
TypeError: fetchMock is not a function
cause Incorrectly importing `fetchMock` when trying to use it as the default export (e.g., `import { fetchMock } from 'fetch-mock'` instead of `import fetchMock from 'fetch-mock'`.)fixEnsure you are using the correct default import: `import fetchMock from 'fetch-mock'`.
Warnings
- breaking fetch-mock became an ESM-only package starting from version 3. Attempting to use `require()` will result in an error in modern Node.js environments.
- breaking Version 9 introduced significant breaking changes, particularly regarding how `fetchMock` is imported and the API for global mocking. The `global` method was also affected.
- gotcha Failing to restore `fetch-mock` after tests can lead to global state pollution, causing unexpected behavior or test failures in subsequent test cases.
- breaking fetch-mock v12 and later require Node.js 18+ for full feature operation, leveraging the native `fetch` API available in these versions. Older Node.js versions may encounter issues.
Install
-
npm install fetch-mock -
yarn add fetch-mock -
pnpm add fetch-mock
Imports
- fetchMock
const fetchMock = require('fetch-mock')import fetchMock from 'fetch-mock'
- sandbox
const sandbox = require('fetch-mock').sandboximport fetchMock, { sandbox } from 'fetch-mock' - FetchMockStatic
import { FetchMockStatic } from 'fetch-mock'import type { FetchMockStatic } from 'fetch-mock'
Quickstart
import fetchMock from 'fetch-mock';
// Mock a GET request to /api/data to return a JSON object
fetchMock.get('/api/data', { data: 'mocked response' });
// Mock a POST request to /api/submit to return a success status
fetchMock.post('/api/submit', 200);
async function fetchDataAndSubmit() {
try {
const dataResponse = await fetch('/api/data');
const data = await dataResponse.json();
console.log('Fetched data:', data); // Should log: { data: 'mocked response' }
const submitResponse = await fetch('/api/submit', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ item: 'new item' })
});
console.log('Submission status:', submitResponse.status); // Should log: 200
// Verify the calls were made
console.log('GET call made:', fetchMock.called('/api/data'));
console.log('POST call made:', fetchMock.called('/api/submit'));
} catch (error) {
console.error('Fetch error:', error);
} finally {
// Restore fetch to its original unmocked state after tests
fetchMock.restore();
}
}
fetchDataAndSubmit();