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

request-matching.mddocs/

Request Matching

Comprehensive matching system supporting URL patterns, HTTP methods, headers, request bodies, and custom matcher functions. The matching system is the core of fetch-mock's flexibility, allowing precise control over which requests get mocked.

Capabilities

URL Matching

Multiple URL matching patterns for different use cases.

type RouteMatcherUrl = string | RegExp | URL | URLMatcherObject;

interface URLMatcherObject {
  begin?: string;
  end?: string;
  include?: string;
  glob?: string;
  express?: string;
  path?: string;
  regexp?: RegExp;
}

Usage Examples:

import fetchMock from "fetch-mock";

// Exact URL match
fetchMock.get("https://api.example.com/users", { body: [] });

// String pattern matching
fetchMock.get("begin:https://api.example.com", { body: "api response" });
fetchMock.get("end:.json", { body: {} });
fetchMock.get("include:users", { body: [] });

// Glob patterns
fetchMock.get("glob:https://api.example.com/users/*", { body: [] });

// Express-style paths with parameters
fetchMock.get("express:/api/users/:id", { body: { id: 1 } });

// Path matching (ignores query/fragment)
fetchMock.get("path:/api/users", { body: [] });

// Regular expressions
fetchMock.get(/\/api\/users\/\d+/, { body: { id: 1 } });

// URL objects
fetchMock.get(new URL("https://api.example.com/users"), { body: [] });

// Multiple patterns
fetchMock.get({
  begin: "https://api.example.com",
  end: ".json",
  include: "users"
}, { body: [] });

Function Matching

Custom matching logic using functions.

type RouteMatcherFunction = (callLog: CallLog) => boolean;

Usage Examples:

// Custom matcher function
fetchMock.get((callLog) => {
  return callLog.url.includes("users") && 
         callLog.options.method === "GET";
}, { body: [] });

// Complex matching logic
fetchMock.route((callLog) => {
  const url = new URL(callLog.url);
  return url.pathname.startsWith("/api/") &&
         url.searchParams.has("token");
}, { body: "authenticated" });

Method Matching

HTTP method matching with case-insensitive support.

interface UserRouteConfig {
  method?: string;
}

Usage Examples:

// Method matching in route config
fetchMock.route({
  url: "/api/users",
  method: "POST",
  response: { status: 201 }
});

// Case insensitive
fetchMock.route({
  url: "/api/users",
  method: "post", // Works with lowercase
  response: { status: 201 }
});

Header Matching

Match requests based on header presence and values.

interface UserRouteConfig {
  headers?: { [key: string]: string | number };
  missingHeaders?: string[];
}

Usage Examples:

// Required headers
fetchMock.route({
  url: "/api/users",
  headers: {
    "Authorization": "Bearer token123",
    "Content-Type": "application/json"
  },
  response: { body: [] }
});

// Headers that must be absent
fetchMock.route({
  url: "/api/public",
  missingHeaders: ["Authorization"],
  response: { body: "public data" }
});

// Partial header matching
fetchMock.route({
  url: "/api/users",
  headers: { "Authorization": "Bearer" }, // Matches any Bearer token
  response: { body: [] }
});

Body Matching

Match requests based on request body content.

interface UserRouteConfig {
  body?: object;
  matchPartialBody?: boolean;
}

Usage Examples:

// Exact body match
fetchMock.post("/api/users", {
  body: { name: "Alice", email: "alice@example.com" },
  response: { status: 201 }
});

// Partial body matching
fetchMock.route({
  url: "/api/users",
  method: "POST",
  body: { name: "Alice" }, // Matches if request body contains name: "Alice"
  matchPartialBody: true,
  response: { status: 201 }
});

// String body matching
fetchMock.post("/api/data", {
  body: "raw text data",
  response: { status: 200 }
});

Query Parameter Matching

Match requests based on URL query parameters.

interface UserRouteConfig {
  query?: { [key: string]: string };
}

Usage Examples:

// Query parameter matching
fetchMock.route({
  url: "/api/users",
  query: { page: "1", limit: "10" },
  response: { body: [] }
});

// Partial query matching
fetchMock.route({
  url: "/api/search",
  query: { q: "test" }, // Matches any request with q=test
  response: { body: { results: [] } }
});

Express Path Parameters

Extract and match path parameters from Express-style routes.

interface UserRouteConfig {
  params?: { [key: string]: string };
}

Usage Examples:

// Path parameter matching
fetchMock.route({
  url: "express:/api/users/:id",
  params: { id: "123" },
  response: { body: { id: 123, name: "Alice" } }
});

// Multiple parameters
fetchMock.route({
  url: "express:/api/users/:userId/posts/:postId",
  params: { userId: "1", postId: "5" },
  response: { body: { userId: 1, postId: 5 } }
});

Custom Matcher Functions

Define reusable custom matchers for complex scenarios.

interface MatcherDefinition {
  name: string;
  matcher: (route: RouteConfig) => RouteMatcherFunction;
  usesBody?: boolean;
}

/**
 * Define a custom matcher that can be reused across routes
 * @param definition - Matcher definition with name and function
 */
defineMatcher(definition: MatcherDefinition): void;

Usage Examples:

// Define custom matcher
fetchMock.defineMatcher({
  name: "hasApiKey",
  matcher: (route) => (callLog) => {
    return callLog.options.headers?.["X-API-Key"] === route.apiKey;
  }
});

// Use custom matcher
fetchMock.route({
  url: "/api/secured",
  hasApiKey: "secret123",
  response: { body: "secure data" }
});

Wildcard Matching

Universal matching patterns.

// Match any URL
any(response: RouteResponse, options?: UserRouteConfig | string): FetchMock;

// Match any URL once
anyOnce(response: RouteResponse, options?: UserRouteConfig | string): FetchMock;

Usage Examples:

// Catch-all route
fetchMock.any({ status: 404, body: "Not found" });

// One-time wildcard
fetchMock.anyOnce({ body: "fallback response" });

Matcher Types

type RouteMatcher = RouteMatcherUrl | RouteMatcherFunction;

type RouteMatcherUrl = string | RegExp | URL | URLMatcherObject;

type RouteMatcherFunction = (callLog: CallLog) => boolean;

interface URLMatcherObject {
  begin?: string;    // URL starts with string
  end?: string;      // URL ends with string
  include?: string;  // URL contains string
  glob?: string;     // Glob pattern match
  express?: string;  // Express-style path
  path?: string;     // Exact path match (ignoring query/fragment)
  regexp?: RegExp;   // Regular expression
}