or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

conditional-mocking.mderror-abort-handling.mdindex.mdmock-management.mdresponse-mocking.md
tile.json

tessl/npm-jest-fetch-mock

Comprehensive fetch API mocking solution for Jest testing environments with configurable responses and TypeScript support

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

To install, run

npx @tessl/cli install tessl/npm-jest-fetch-mock@3.0.0

index.mddocs/

Jest Fetch Mock

Jest Fetch Mock provides a comprehensive mocking solution for the fetch API in Jest testing environments. It enables developers to easily mock HTTP requests made with fetch() by providing configurable mock responses, supporting both successful and failed request scenarios, and offering utilities for inspecting mock call history.

Package Information

  • Package Name: jest-fetch-mock
  • Package Type: npm
  • Language: JavaScript/TypeScript
  • Installation: npm install --save-dev jest-fetch-mock

Core Imports

const fetchMock = require("jest-fetch-mock");

For ES6/TypeScript:

import fetchMock from "jest-fetch-mock";
// or
import { enableFetchMocks, disableFetchMocks } from "jest-fetch-mock";

Basic Usage

// Enable mocking in setup file
require("jest-fetch-mock").enableMocks();

// In your test
beforeEach(() => {
  fetch.resetMocks();
});

it("should fetch users", async () => {
  fetch.mockResponseOnce(JSON.stringify({ users: ["Alice", "Bob"] }));
  
  const response = await fetch("/users");
  const data = await response.json();
  
  expect(data.users).toEqual(["Alice", "Bob"]);
  expect(fetch.mock.calls.length).toEqual(1);
  expect(fetch.mock.calls[0][0]).toEqual("/users");
});

Architecture

Jest Fetch Mock is built around several key components:

  • Fetch Mock Function: Drop-in replacement for native fetch with Jest mock capabilities
  • Response Mocking: Flexible system for mocking successful HTTP responses
  • Error/Rejection Mocking: Support for mocking network failures and HTTP errors
  • Conditional Mocking: URL-based and predicate-based selective mocking
  • Global Setup: Integration with Jest's global mocking system
  • TypeScript Support: Complete type definitions for all functionality

Capabilities

Response Mocking

Core functionality for mocking successful HTTP responses with configurable bodies and options. Supports both one-time and persistent mocks.

// Mock single response for all calls
fetch.mockResponse(bodyOrFunction, init);

// Mock single response for next call only
fetch.mockResponseOnce(bodyOrFunction, init);

// Alias for mockResponseOnce
fetch.once(bodyOrFunction, init);

// Mock multiple responses in sequence
fetch.mockResponses(...responses);

Response Mocking

Error and Abort Handling

Functionality for mocking network failures, HTTP errors, and request aborts. Essential for testing error handling in your application.

// Mock rejection with error
fetch.mockReject(errorOrFunction);
fetch.mockRejectOnce(errorOrFunction);

// Mock request abort
fetch.mockAbort();
fetch.mockAbortOnce();

Error and Abort Handling

Conditional Mocking

Advanced mocking capabilities that allow selective mocking based on URL patterns or custom predicates. Enables fine-grained control over which requests are mocked.

// Check if request should be mocked
fetch.isMocking(input, reqInit);

// Conditional mocking based on URL/predicate
fetch.mockIf(urlOrPredicate, bodyOrFunction, init);
fetch.dontMockIf(urlOrPredicate, bodyOrFunction, init);

// Enable/disable mocking globally
fetch.doMock(bodyOrFunction, init);
fetch.dontMock();

Conditional Mocking

Mock Management

Utilities for managing mock state, resetting mocks between tests, and controlling global mocking behavior.

// Reset mock state
fetch.resetMocks();

// Global mock control
fetch.enableMocks();
fetch.disableMocks();

Mock Management

Types

interface FetchMock extends jest.MockInstance<Promise<Response>, [string | Request | undefined, RequestInit | undefined]> {
  (input?: string | Request, init?: RequestInit): Promise<Response>;
  // All methods documented in capability sections above
}

interface MockParams {
  status?: number;
  statusText?: string;
  headers?: string[][] | { [key: string]: string };
  url?: string;
}

interface MockResponseInit extends MockParams {
  body?: string;
  init?: MockParams;
}

type ErrorOrFunction = Error | ((...args: any[]) => Promise<any>);
type UrlOrPredicate = string | RegExp | ((input: Request) => boolean);
type MockResponseInitFunction = (request: Request) => Promise<MockResponseInit | string>;

Properties

// Web API constructors available on fetch object
fetch.Headers; // Native Headers constructor
fetch.Response; // Custom Response wrapper with mock support  
fetch.Request; // Native Request constructor