Fetch Mocking Library

12.6.0 · active · verified Wed Apr 22

fetch-mock is a comprehensive library for mocking HTTP requests made using the `fetch` API in JavaScript and TypeScript applications. It is widely used in testing environments to isolate network calls and control their responses. The current stable version is `12.6.0`, with a generally active release cadence, often seeing patch updates multiple times a month to address bug fixes and introduce minor features. Key differentiators include its extensive support for the `fetch` API specification, including advanced behaviors like streaming and aborting requests. It offers declarative matching for various aspects of an HTTP request (URL, headers, body, query parameters), provides convenient shorthands for common scenarios, supports delaying responses, and can function as a spy to observe real network activity. The library is isomorphic, working equally well in Node.js (requiring Node.js 18+ for full feature operation) and modern browser environments, and can be extended with custom matchers.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to mock both GET and POST requests using `fetch-mock`, make `fetch` calls against the mocked endpoints, and verify that the mocks were called. It also shows how to restore `fetch` to its original state.

import fetchMock from 'fetch-mock';

// Mock a GET request to /api/data to return a JSON object
fetchMock.get('/api/data', { data: 'mocked response' });

// Mock a POST request to /api/submit to return a success status
fetchMock.post('/api/submit', 200);

async function fetchDataAndSubmit() {
  try {
    const dataResponse = await fetch('/api/data');
    const data = await dataResponse.json();
    console.log('Fetched data:', data); // Should log: { data: 'mocked response' }

    const submitResponse = await fetch('/api/submit', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ item: 'new item' })
    });
    console.log('Submission status:', submitResponse.status); // Should log: 200

    // Verify the calls were made
    console.log('GET call made:', fetchMock.called('/api/data'));
    console.log('POST call made:', fetchMock.called('/api/submit'));
  } catch (error) {
    console.error('Fetch error:', error);
  } finally {
    // Restore fetch to its original unmocked state after tests
    fetchMock.restore();
  }
}

fetchDataAndSubmit();

view raw JSON →