Registry / testing / fetch-mock

fetch-mock

JSON →
library12.6.0jsnpmunverified

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.

npm install fetch-mock
INSTALL
IMPORT
SIG · FETCH-MOCK
F
fetch-mock
testingjavascriptv12.6.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

fetchMock
import fetchMock from 'fetch-mock'
const fetchMock = require('fetch-mock')
The library transitioned to being ESM-only from v3 onwards. `require()` will not work in modern versions.
sandbox
import fetchMock, { sandbox } from 'fetch-mock'
const sandbox = require('fetch-mock').sandbox
The `sandbox` utility is a named export that allows mocking a local `fetch` instance without affecting the global one. Requires default import of `fetchMock` alongside it.
FetchMockStatic
import type { FetchMockStatic } from 'fetch-mock'
import { FetchMockStatic } from 'fetch-mock'
This is a TypeScript type definition for the main fetch-mock instance, intended for type imports only.

This example demonstrates how to mock both GET and POST requests using `fetch-mock`, make `fetch` calls against the mocked endpoints, and verify that the mocks were called. It also shows how to restore `fetch` to its original state.

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();
Debug
Known issues
breakingfetch-mock became an ESM-only package starting from version 3. Attempting to use `require()` will result in an error in modern Node.js environments.
fix
Migrate all `require()` statements for `fetch-mock` to ES module `import` statements. Ensure your project is configured for ESM (e.g., `"type": "module"` in `package.json`).
affects: >=3.0.0
breakingVersion 9 introduced significant breaking changes, particularly regarding how `fetchMock` is imported and the API for global mocking. The `global` method was also affected.
fix
Review the official migration guide for `fetch-mock@9` on the project's website or GitHub repository, as the API for global mocking and default exports changed significantly.
affects: >=9.0.0
gotchaFailing to restore `fetch-mock` after tests can lead to global state pollution, causing unexpected behavior or test failures in subsequent test cases.
fix
Always call `fetchMock.restore()` or `fetchMock.reset()` in an `afterEach` or `afterAll` hook within your testing framework to ensure a clean state.
affects: *
breakingfetch-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.
fix
Ensure your Node.js environment is version 18 or higher. If using an older version, you may need to explicitly polyfill `fetch` (e.g., with `node-fetch`) and ensure `fetch-mock` is compatible with that setup.
affects: >=12.0.0
Errors
Common errors & fixes
Error [ERR_REQUIRE_ESM]: require() of ES Module ... fetch-mock/index.js not supported.
Attempting to use `require()` to import `fetch-mock` in a context where it expects an ES module.
fix
Change `const fetchMock = require('fetch-mock')` to `import fetchMock from 'fetch-mock'`.
ReferenceError: fetch is not defined
Running tests in a Node.js environment older than version 18 without a global `fetch` polyfill or `node-fetch` installed.
fix
Upgrade 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
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'`.)
fix
Ensure you are using the correct default import: `import fetchMock from 'fetch-mock'`.
Upgrade
Version history
12.6.0latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
6 hits · last 30 days
node
6
Resources
fetch-mock — npm install fetch-mock · libregistry