Registry / testing / mock-fetch

mock-fetch

JSON →
library1.0.0jsnpmunverified

Mock the browser's fetch API for testing. Version 1.0.0 provides a simple way to intercept fetch calls in tests. Lightweight library with no dependencies. Differentiates from alternatives like jest-fetch-mock by providing a simpler API focused solely on mocking fetch.

npm install mock-fetch
INSTALL
IMPORT
SIG · MOCK-FETCH
M
mock-fetch
testingjavascriptv1.0.0
harness data pending
Install & Compatibility
Where this runs

No compatibility data collected yet for this library.

Code
Verified usage

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

mockFetch
import { mockFetch } from 'mock-fetch'
import mockFetch from 'mock-fetch'
Named export; default import is not supported.
MockResponse
import { MockResponse } from 'mock-fetch'
import { MockResponse } from 'mock-fetch/mock-response'
Type export for TypeScript users.
FetchMock
import type { FetchMock } from 'mock-fetch'
Type import for TypeScript when using the mock instance type.

Demonstrates basic mocking of a fetch request with a JSON response.

import { mockFetch } from 'mock-fetch'; // Mock a single fetch call mockFetch('https://api.example.com/data', { status: 200, body: { key: 'value' } }); // Use fetch in your code fetch('https://api.example.com/data') .then(res => res.json()) .then(data => console.log(data)); // { key: 'value' }
Debug
Known issues
gotchamockFetch does not reset between tests automatically. Manually clear mocks in afterEach if using globally.
fix
Call mockFetch.clear() in afterEach hook.
affects: <=1.0.0
gotchaOnly the browser fetch API is supported; does not work with Node.js without polyfill.
fix
Install and import 'whatwg-fetch' or use Node 18+.
affects: >=0.0.0
Errors
Common errors & fixes
TypeError: mockFetch is not a function
Incorrect import (default instead of named).
fix
Use `import { mockFetch } from 'mock-fetch'`.
Upgrade
Version history
1.0.0latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
3 hits · last 30 days
node
2
Amazon
1
Resources
mock-fetch — npm install mock-fetch · libregistry