{"id":16360,"library":"fetch-mock","title":"Fetch Mocking Library","description":"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.","status":"active","version":"12.6.0","language":"javascript","source_language":"en","source_url":"https://github.com/wheresrhys/fetch-mock","tags":["javascript","fetch","http","mock","testing","spy","stub","typescript"],"install":[{"cmd":"npm install fetch-mock","lang":"bash","label":"npm"},{"cmd":"yarn add fetch-mock","lang":"bash","label":"yarn"},{"cmd":"pnpm add fetch-mock","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The library transitioned to being ESM-only from v3 onwards. `require()` will not work in modern versions.","wrong":"const fetchMock = require('fetch-mock')","symbol":"fetchMock","correct":"import fetchMock from 'fetch-mock'"},{"note":"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.","wrong":"const sandbox = require('fetch-mock').sandbox","symbol":"sandbox","correct":"import fetchMock, { sandbox } from 'fetch-mock'"},{"note":"This is a TypeScript type definition for the main fetch-mock instance, intended for type imports only.","wrong":"import { FetchMockStatic } from 'fetch-mock'","symbol":"FetchMockStatic","correct":"import type { FetchMockStatic } from 'fetch-mock'"}],"quickstart":{"code":"import fetchMock from 'fetch-mock';\n\n// Mock a GET request to /api/data to return a JSON object\nfetchMock.get('/api/data', { data: 'mocked response' });\n\n// Mock a POST request to /api/submit to return a success status\nfetchMock.post('/api/submit', 200);\n\nasync function fetchDataAndSubmit() {\n  try {\n    const dataResponse = await fetch('/api/data');\n    const data = await dataResponse.json();\n    console.log('Fetched data:', data); // Should log: { data: 'mocked response' }\n\n    const submitResponse = await fetch('/api/submit', {\n      method: 'POST',\n      headers: { 'Content-Type': 'application/json' },\n      body: JSON.stringify({ item: 'new item' })\n    });\n    console.log('Submission status:', submitResponse.status); // Should log: 200\n\n    // Verify the calls were made\n    console.log('GET call made:', fetchMock.called('/api/data'));\n    console.log('POST call made:', fetchMock.called('/api/submit'));\n  } catch (error) {\n    console.error('Fetch error:', error);\n  } finally {\n    // Restore fetch to its original unmocked state after tests\n    fetchMock.restore();\n  }\n}\n\nfetchDataAndSubmit();","lang":"typescript","description":"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."},"warnings":[{"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`).","message":"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.","severity":"breaking","affected_versions":">=3.0.0"},{"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.","message":"Version 9 introduced significant breaking changes, particularly regarding how `fetchMock` is imported and the API for global mocking. The `global` method was also affected.","severity":"breaking","affected_versions":">=9.0.0"},{"fix":"Always call `fetchMock.restore()` or `fetchMock.reset()` in an `afterEach` or `afterAll` hook within your testing framework to ensure a clean state.","message":"Failing to restore `fetch-mock` after tests can lead to global state pollution, causing unexpected behavior or test failures in subsequent test cases.","severity":"gotcha","affected_versions":"*"},{"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.","message":"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.","severity":"breaking","affected_versions":">=12.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Change `const fetchMock = require('fetch-mock')` to `import fetchMock from 'fetch-mock'`.","cause":"Attempting to use `require()` to import `fetch-mock` in a context where it expects an ES module.","error":"Error [ERR_REQUIRE_ESM]: require() of ES Module ... fetch-mock/index.js not supported."},{"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.","cause":"Running tests in a Node.js environment older than version 18 without a global `fetch` polyfill or `node-fetch` installed.","error":"ReferenceError: fetch is not defined"},{"fix":"Ensure you are using the correct default import: `import fetchMock from 'fetch-mock'`.","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'`.)","error":"TypeError: fetchMock is not a function"}],"ecosystem":"npm"}