View on GitHub


Mock http requests made using fetch

V5 Installation

Install fetch-mock using npm install --save-dev fetch-mock

In most environments use const fetchMock = require('fetch-mock') to use it in your code. Some exceptions include:

Global fetch

By default fetch-mock assumes fetch is a global so once you’ve required fetch-mock refer to the quickstart and api docs.

Polyfilling fetch

Many older browsers will require polyfilling the fetch global

Non-global fetch

When using a non-global fetch implementation (such as node-fetch or fetch-ponyfill) use the sandbox() method to return a function that can be used as a replacement for fetch, and be passed into your source code using your choice of mocking library. The function returned by sandbox() supports the full fetch-mock api so once generated it can be worked with as if it were the original fetch-mock object, e.g.

const fetchMock = require('fetch-mock');
const myMock = fetchMock.sandbox().mock('/home', 200);
// pass myMock in to your application code, instead of fetch, run it, then...

References to Request, Response, Helpers and Promise

If you’re using a non-global fetch implementation, or wish to use a custom Promise implementation, you may need to tell fetch-mock to use these when matching requests and returning responses. Do this using the .setImplementations() method. e.g.

fetchMock.setImplementations({Promise: require('Bluebird').promise})

In particular, when using fetch-ponyfill


will set all the internal references to point at fetch-ponyfill’s classes.