Instance creation, global mocking, and lifecycle management for different testing scenarios. The instance management system provides flexible control over how fetch-mock integrates with your application and testing environment.
Create isolated fetch-mock instances for independent testing scenarios.
/**
* Create a new FetchMock instance with inherited configuration
* @returns New FetchMock instance
*/
createInstance(): FetchMock;Usage Examples:
import fetchMock from "fetch-mock";
// Create isolated instances for different test suites
const apiMock = fetchMock.createInstance();
const authMock = fetchMock.createInstance();
// Configure each instance independently
apiMock.get("/api/users", { body: [] });
authMock.post("/auth/login", { status: 200, body: { token: "abc123" } });
// Instances don't interfere with each other
expect(apiMock.called()).toBe(false);
expect(authMock.called()).toBe(false);Replace the global fetch function with fetch-mock's handler.
/**
* Replace global fetch with this instance's fetch handler
* @returns FetchMock instance for chaining
*/
mockGlobal(): FetchMock;
/**
* Restore the original global fetch function
* @returns FetchMock instance for chaining
*/
unmockGlobal(): FetchMock;Usage Examples:
// Mock global fetch
fetchMock
.get("/api/users", { body: [] })
.mockGlobal();
// Now all fetch calls are mocked
const response = await fetch("/api/users");
const users = await response.json();
// Restore original fetch
fetchMock.unmockGlobal();
// Global fetch is back to normal
const realResponse = await fetch("https://httpbin.org/json");Monitor real network requests while recording call history.
/**
* Create a spy route that passes requests to the real network
* @param matcher - Optional URL pattern to spy on specific routes
* @param name - Optional route name for identification
* @returns FetchMock instance for chaining
*/
spy(matcher?: RouteMatcher | UserRouteConfig, name?: RouteName): FetchMock;
/**
* Enable global spying (spy + mockGlobal combination)
* @returns FetchMock instance for chaining
*/
spyGlobal(): FetchMock;Usage Examples:
// Spy on all requests (pass through to network)
fetchMock.spy().mockGlobal();
// Make real requests that are recorded
await fetch("https://httpbin.org/json");
expect(fetchMock.called()).toBe(true);
// Spy on specific URLs only
fetchMock
.spy("https://api.example.com/analytics", "analytics")
.get("https://api.example.com/users", { body: [] }) // Mock this one
.mockGlobal();
// Analytics calls go to real network, user calls are mocked
await fetch("https://api.example.com/analytics"); // Real network
await fetch("https://api.example.com/users"); // Mocked
expect(fetchMock.called("analytics")).toBe(true);
// Global spy shorthand
fetchMock.spyGlobal(); // Equivalent to spy().mockGlobal()Remove and modify existing routes during testing.
/**
* Remove routes based on specified criteria
* @param options - Removal options
* @returns FetchMock instance for chaining
*/
removeRoutes(options?: RemoveRouteOptions): FetchMock;
/**
* Remove a specific route by name
* @param routeName - Name of the route to remove
* @returns FetchMock instance for chaining
*/
removeRoute(routeName: string): FetchMock;
/**
* Modify an existing route's configuration
* @param routeName - Name of the route to modify
* @param options - New configuration options
* @returns FetchMock instance for chaining
*/
modifyRoute(routeName: string, options: ModifyRouteConfig): FetchMock;
interface RemoveRouteOptions {
includeSticky?: boolean; // Remove sticky routes (default: false)
includeFallback?: boolean; // Remove fallback route (default: true)
names?: string[]; // Remove specific named routes
}Usage Examples:
// Set up some routes
fetchMock
.get("/api/users", { body: [] }, { name: "users" })
.post("/api/users", { status: 201 }, { name: "create-user" })
.sticky("/api/health", { body: "ok" }, { name: "health" })
.catch({ status: 404 });
// Remove all routes (except sticky)
fetchMock.removeRoutes();
// Remove sticky routes too
fetchMock.removeRoutes({ includeSticky: true });
// Remove specific routes by name
fetchMock.removeRoutes({ names: ["users", "create-user"] });
// Remove single route
fetchMock.removeRoute("users");
// Modify existing route
fetchMock.modifyRoute("users", {
response: { body: [{ id: 1, name: "Alice" }] },
delay: 500
});Full reset of all routes, history, and global mocking state.
/**
* Complete reset: remove routes, clear history, unmock global
* @param options - Reset options
* @returns FetchMock instance for chaining
*/
hardReset(options?: HardResetOptions): FetchMock;
interface HardResetOptions {
includeSticky?: boolean; // Include sticky routes in reset
}Usage Examples:
// Complete reset (keeps sticky routes)
fetchMock.hardReset();
// Reset everything including sticky routes
fetchMock.hardReset({ includeSticky: true });
// Equivalent to:
// fetchMock.clearHistory().removeRoutes({ includeSticky: true }).unmockGlobal();Access and modify instance configuration.
interface FetchMockConfig {
includeContentLength?: boolean; // Include content-length header (default: true)
matchPartialBody?: boolean; // Allow partial body matching (default: false)
allowRelativeUrls?: boolean; // Allow relative URLs in Node.js (default: false)
fetch?: typeof fetch; // Original fetch function
Headers?: typeof Headers; // Headers constructor
Request?: typeof Request; // Request constructor
Response?: typeof Response; // Response constructor
}Usage Examples:
// Access current configuration
console.log(fetchMock.config.includeContentLength);
// Modify configuration
fetchMock.config.matchPartialBody = true;
fetchMock.config.allowRelativeUrls = true;
// Create instance with custom configuration
const customMock = new FetchMock({
includeContentLength: false,
matchPartialBody: true,
allowRelativeUrls: true
});Direct access to the underlying fetch handler for advanced scenarios.
/**
* The main fetch handler function
* @param requestInput - URL, Request object, or other input
* @param requestInit - Request initialization options
* @returns Promise resolving to Response
*/
fetchHandler(requestInput: string | URL | Request, requestInit?: RequestInit): Promise<Response>;Usage Examples:
// Use fetch handler directly
const response = await fetchMock.fetchHandler("https://api.example.com/users");
// Custom integration
const customFetch = fetchMock.fetchHandler;
global.fetch = customFetch;
// Handler has reference to parent instance
console.log(fetchMock.fetchHandler.fetchMock === fetchMock); // true// Jest example
beforeEach(() => {
fetchMock.reset();
});
afterEach(() => {
fetchMock.restore();
});
// Vitest example
import { beforeEach, afterEach } from 'vitest';
beforeEach(() => {
fetchMock.hardReset();
});
// Node.js testing with isolated instances
const testMock = fetchMock.createInstance();
// Use testMock instead of global fetchMock// Browser environment
import fetchMock from "fetch-mock";
fetchMock.mockGlobal(); // Replaces window.fetch
// Node.js environment with custom fetch
import fetch from "node-fetch";
import { FetchMock } from "fetch-mock";
const fetchMock = new FetchMock({
fetch: fetch,
Headers: fetch.Headers,
Request: fetch.Request,
Response: fetch.Response
});interface HardResetOptions {
includeSticky?: boolean;
}
interface RemoveRouteOptions {
includeSticky?: boolean;
includeFallback?: boolean;
names?: string[];
}
interface ModifyRouteConfig {
method?: string | null;
headers?: { [key: string]: string | number } | null;
missingHeaders?: string[] | null;
query?: { [key: string]: string } | null;
params?: { [key: string]: string } | null;
body?: object | null;
matcherFunction?: RouteMatcherFunction | null;
url?: RouteMatcherUrl | null;
response?: RouteResponse | RouteResponseFunction | null;
repeat?: number | null;
delay?: number | null;
waitFor?: RouteName | RouteName[] | null;
}
interface FetchMockConfig {
includeContentLength?: boolean;
matchPartialBody?: boolean;
allowRelativeUrls?: boolean;
fetch?: typeof fetch;
Headers?: typeof Headers;
Request?: typeof Request;
Response?: typeof Response;
}