What is fetch-mock?
fetch-mock is a library for mocking HTTP requests made using the Fetch API. It allows developers to simulate different responses and behaviors for fetch calls, which is particularly useful for testing and development purposes.
What are fetch-mock's main functionalities?
Mocking a simple GET request
This feature allows you to mock a simple GET request. The code sample demonstrates how to mock a GET request to 'https://api.example.com/data' and return a JSON object with sample data.
const fetchMock = require('fetch-mock');
fetchMock.get('https://api.example.com/data', { data: 'sample data' });
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data));
Mocking a POST request with specific body
This feature allows you to mock a POST request with a specific request body. The code sample demonstrates how to mock a POST request to 'https://api.example.com/submit' and return different responses based on the request body.
const fetchMock = require('fetch-mock');
fetchMock.post('https://api.example.com/submit', (url, options) => {
if (options.body === JSON.stringify({ key: 'value' })) {
return { status: 'success' };
} else {
return { status: 'error' };
}
});
fetch('https://api.example.com/submit', {
method: 'POST',
body: JSON.stringify({ key: 'value' })
})
.then(response => response.json())
.then(data => console.log(data));
Mocking with delay
This feature allows you to mock a request with a delay. The code sample demonstrates how to mock a GET request to 'https://api.example.com/delayed' and return a response after a 1-second delay.
const fetchMock = require('fetch-mock');
fetchMock.get('https://api.example.com/delayed', new Promise(resolve => setTimeout(() => resolve({ data: 'delayed data' }), 1000)));
fetch('https://api.example.com/delayed')
.then(response => response.json())
.then(data => console.log(data));
Mocking with different response statuses
This feature allows you to mock requests with different HTTP response statuses. The code sample demonstrates how to mock a GET request to 'https://api.example.com/not-found' and return a 404 status.
const fetchMock = require('fetch-mock');
fetchMock.get('https://api.example.com/not-found', 404);
fetch('https://api.example.com/not-found')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.catch(error => console.error('Fetch error:', error));
Other packages similar to fetch-mock
nock
Nock is a HTTP mocking and expectations library for Node.js. It intercepts HTTP requests and allows you to define custom responses. Compared to fetch-mock, Nock is more focused on Node.js and works with any HTTP library, not just fetch.
msw
Mock Service Worker (MSW) is a library for mocking network requests in both browser and Node.js environments. It uses Service Workers to intercept requests in the browser, making it more versatile for front-end testing compared to fetch-mock.
axios-mock-adapter
Axios Mock Adapter is a library specifically designed for mocking requests made with the Axios HTTP client. It provides a simple API for defining request handlers and responses. While fetch-mock is designed for the Fetch API, axios-mock-adapter is tailored for Axios.
fetch-mock
Mock http requests made using fetch.
Features include:
- mocks most of the fetch API spec, even advanced behaviours such as streaming and aborting
- declarative matching for most aspects of a http request, including url, headers, body and query parameters
- shorthands for the most commonly used features, such as matching a http method or matching one fetch only
- support for delaying responses, or using your own async functions to define custom race conditions
- can be used as a spy to observe real network requests
- can be extended with your own reusable custom matchers that can be used both for matching fetch-calls and inspecting the results
- isomorphic, and supports either a global fetch instance or a locally required instance
New If using jest, try the new fetch-mock-jest wrapper.
New Cheatsheet
fetchMock.mock('http://example.com', 200);
const res = await fetch('http://example.com');
assert(res.ok);
fetchMock.restore();
Table of Contents
I devote a lot of time to maintaining fetch-mock for free. I don't ask for payment, but am raising money for a refugee charity - please consider donating
Requirements
fetch-mock requires the following to run:
- Node.js 8+ for full feature operation
- Node.js 0.12+ with limitations
- npm (normally comes with Node.js)
- Either of the following
- node-fetch when testing in a nodejs
- A browser that supports the
fetch
API when testing in a browser
Documentation and Usage
See the project website or cheatsheet
If you're using jest as your test runner, consider using fetch-mock-jest, a lightweight, jest-friendly wrapper around fetch-mock.
License
fetch-mock is licensed under the MIT license.
Copyright © 2019, Rhys Evans
Housekeeping