fetch-mock is a comprehensive HTTP request mocking library specifically designed for the Fetch API, enabling developers to mock, spy on, and test HTTP requests in both Node.js and browser environments. It offers declarative matching capabilities for URLs, headers, request bodies, and query parameters, with flexible response configuration and complete call history inspection.
This package is part of a larger ecosystem that includes specialized testing framework integrations and migration tools.
npm install fetch-mockimport fetchMock from "fetch-mock";For named imports:
import {
FetchMock,
FetchMockConfig,
defaultFetchMockConfig,
CallLog,
CallHistoryFilter,
RouteMatcher,
MatcherDefinition,
UserRouteConfig,
RouteResponse,
RouteName,
ModifyRouteConfig,
RouteConfigWrapper,
RemoveRouteOptions
} from "fetch-mock";For CommonJS:
const fetchMock = require("fetch-mock");import fetchMock from "fetch-mock";
// Mock a simple GET request
fetchMock.get("https://api.example.com/users", [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" }
]);
// Make the request (in your code)
const response = await fetch("https://api.example.com/users");
const users = await response.json();
// Verify the call was made
expect(fetchMock.called("https://api.example.com/users")).toBe(true);
// Clean up
fetchMock.restore();The fetch-mock ecosystem includes specialized packages for different testing frameworks and migration scenarios:
mockClear(), mockReset(), and mockRestore() methods that integrate with Jest's mock management systemfetch-mock is built around several key components:
Core route definition methods for mocking HTTP requests with flexible matching and response configuration.
// Main route method
route(matcher: RouteMatcher | UserRouteConfig, response?: RouteResponse, options?: UserRouteConfig | string): FetchMock;
// HTTP method shortcuts
get(matcher: RouteMatcher, response: RouteResponse, options?: UserRouteConfig | string): FetchMock;
post(matcher: RouteMatcher, response: RouteResponse, options?: UserRouteConfig | string): FetchMock;
put(matcher: RouteMatcher, response: RouteResponse, options?: UserRouteConfig | string): FetchMock;
delete(matcher: RouteMatcher, response: RouteResponse, options?: UserRouteConfig | string): FetchMock;
head(matcher: RouteMatcher, response: RouteResponse, options?: UserRouteConfig | string): FetchMock;
patch(matcher: RouteMatcher, response: RouteResponse, options?: UserRouteConfig | string): FetchMock;
// One-time method shortcuts
getOnce(matcher: RouteMatcher, response: RouteResponse, options?: UserRouteConfig | string): FetchMock;
postOnce(matcher: RouteMatcher, response: RouteResponse, options?: UserRouteConfig | string): FetchMock;
putOnce(matcher: RouteMatcher, response: RouteResponse, options?: UserRouteConfig | string): FetchMock;
deleteOnce(matcher: RouteMatcher, response: RouteResponse, options?: UserRouteConfig | string): FetchMock;
headOnce(matcher: RouteMatcher, response: RouteResponse, options?: UserRouteConfig | string): FetchMock;
patchOnce(matcher: RouteMatcher, response: RouteResponse, options?: UserRouteConfig | string): FetchMock;
// Special route types
once(matcher: RouteMatcher, response: RouteResponse, options?: UserRouteConfig | string): FetchMock;
sticky(matcher: RouteMatcher, response: RouteResponse, options?: UserRouteConfig | string): FetchMock;
any(response: RouteResponse, options?: UserRouteConfig | string): FetchMock;
anyOnce(response: RouteResponse, options?: UserRouteConfig | string): FetchMock;
// Fallback and spying
catch(response?: RouteResponse): FetchMock;
spy(matcher?: RouteMatcher | UserRouteConfig, name?: RouteName): FetchMock;Comprehensive matching system supporting URL patterns, HTTP methods, headers, request bodies, and custom matcher functions.
type RouteMatcher = string | RegExp | URL | URLMatcherObject | RouteMatcherFunction;
interface URLMatcherObject {
begin?: string;
end?: string;
include?: string;
glob?: string;
express?: string;
path?: string;
regexp?: RegExp;
}
type RouteMatcherFunction = (callLog: CallLog) => boolean;Flexible response configuration supporting status codes, headers, body content, delays, errors, and dynamic responses.
type RouteResponse = RouteResponseData | RouteResponsePromise | RouteResponseFunction;
interface RouteResponseConfig {
body?: BodyInit | object;
status?: number;
headers?: { [key: string]: string };
throws?: Error;
redirectUrl?: string;
options?: ResponseInit;
}
type RouteResponseFunction = (callLog: CallLog) => RouteResponseData | RouteResponsePromise;Complete call history tracking and inspection capabilities for verifying request patterns and debugging. All call history methods are accessed through the callHistory property.
// Access call history through callHistory property
interface CallHistory {
called(filter?: CallHistoryFilter, options?: RouteConfig): boolean;
calls(filter?: CallHistoryFilter, options?: RouteConfig): CallLog[];
lastCall(filter?: CallHistoryFilter, options?: RouteConfig): CallLog | undefined;
done(routeNames?: RouteName | RouteName[]): boolean;
flush(waitForResponseMethods?: boolean): Promise<void>;
clear(): void;
}Instance creation, global mocking, lifecycle management, and route modification for different testing scenarios.
// Instance management
createInstance(): FetchMock;
mockGlobal(): FetchMock;
unmockGlobal(): FetchMock;
spyGlobal(): FetchMock;
hardReset(options?: HardResetOptions): FetchMock;
// Route management
removeRoutes(options?: RemoveRouteOptions): FetchMock;
removeRoute(routeName: string): FetchMock;
modifyRoute(routeName: string, options: ModifyRouteConfig): FetchMock;
clearHistory(): FetchMock;
// Matcher definition
defineMatcher(matcher: MatcherDefinition): void;interface CallLog {
args: unknown[];
url: string;
options: NormalizedRequestOptions;
request?: Request;
signal?: AbortSignal;
response?: Response;
route?: Route;
expressParams?: { [x: string]: string };
queryParams?: URLSearchParams;
pendingPromises: Promise<unknown>[];
}
type FetchMockGlobalConfig = {
includeContentLength?: boolean;
matchPartialBody?: boolean;
allowRelativeUrls?: boolean;
};
type FetchImplementations = {
fetch?: typeof fetch;
Headers?: typeof Headers;
Request?: typeof Request;
Response?: typeof Response;
};
type FetchMockConfig = FetchMockGlobalConfig & FetchImplementations;
const defaultFetchMockConfig: FetchMockConfig;
type CallHistoryFilter = RouteName | 'matched' | 'unmatched' | boolean | RouteMatcher;
type RouteName = string;
interface HardResetOptions {
includeSticky?: boolean;
}
interface RemoveRouteOptions {
includeSticky?: boolean;
includeFallback?: boolean;
names?: string[];
}
interface ModifyRouteConfig {
method?: string | null;
headers?: { [key: string]: string | number } | null;
query?: { [key: string]: string } | null;
body?: object | null;
response?: RouteResponse | null;
repeat?: number | null;
delay?: number | null;
}
interface MatcherDefinition {
name: string;
matcher: (route: RouteConfig) => RouteMatcherFunction;
usesBody?: boolean;
}
class RouteConfigWrapper implements UserRouteConfig {
constructor(config: UserRouteConfig);
}