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-mockVerified import paths — ran on the pinned version, not inferred.
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.
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`).
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.
Always call `fetchMock.restore()` or `fetchMock.reset()` in an `afterEach` or `afterAll` hook within your testing framework to ensure a clean state.
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.
Change `const fetchMock = require('fetch-mock')` to `import fetchMock from 'fetch-mock'`.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.Ensure you are using the correct default import: `import fetchMock from 'fetch-mock'`.
No dependency data recorded yet.