or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

call-history.mdindex.mdinstance-management.mdrequest-matching.mdresponse-configuration.mdroute-definition.md
tile.json

tessl/npm-fetch-mock

Mock http requests made using fetch

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/fetch-mock@12.5.x

To install, run

npx @tessl/cli install tessl/npm-fetch-mock@12.5.0

index.mddocs/

fetch-mock

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.

Package Information

  • Package Name: fetch-mock
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install fetch-mock

Core Imports

import 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");

Basic Usage

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();

Ecosystem

The fetch-mock ecosystem includes specialized packages for different testing frameworks and migration scenarios:

Testing Framework Integrations

  • @fetch-mock/jest (v0.2.17): Jest-specific wrapper adding mockClear(), mockReset(), and mockRestore() methods that integrate with Jest's mock management system
  • @fetch-mock/vitest (v0.2.15): Vitest-specific wrapper with similar mock lifecycle methods that integrate with Vitest's mock management

Migration Tools

  • @fetch-mock/codemods (v0.1.3): JSCodeshift-based codemods for automatically upgrading fetch-mock usage patterns in existing codebases

Architecture

fetch-mock is built around several key components:

  • FetchMock Instance: Main class providing route definition, call inspection, and global mocking
  • Router System: Internal routing engine that matches requests to configured routes
  • Call History: Complete logging and inspection of all mocked requests
  • Matcher System: Flexible URL, method, header, and body matching with custom matcher support
  • Response Engine: Configurable response generation including delays, errors, and dynamic responses

Capabilities

Route Definition

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;

Route Definition

Request Matching

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;

Request Matching

Response Configuration

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;

Response Configuration

Call History & Inspection

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;
}

Call History & Inspection

Instance Management

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;

Instance Management

Core Types

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);
}