Comprehensive fetch API mocking solution for Jest testing environments with configurable responses and TypeScript support
npx @tessl/cli install tessl/npm-jest-fetch-mock@3.0.0Jest 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.
npm install --save-dev jest-fetch-mockconst fetchMock = require("jest-fetch-mock");For ES6/TypeScript:
import fetchMock from "jest-fetch-mock";
// or
import { enableFetchMocks, disableFetchMocks } from "jest-fetch-mock";// 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");
});Jest Fetch Mock is built around several key components:
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);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();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();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();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>;// 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