What is fetch-mock-jest?
fetch-mock-jest is a library that allows you to mock fetch calls in your Jest tests. It provides a simple and powerful way to simulate different responses from the fetch API, making it easier to test your code's behavior under various conditions.
What are fetch-mock-jest's main functionalities?
Mocking a simple fetch request
This feature allows you to mock a simple fetch request and provide a predefined response. In this example, the fetch call to '/api/data' will return a JSON object with data '12345'.
const fetchMock = require('fetch-mock-jest');
fetchMock.mockResponseOnce(JSON.stringify({ data: '12345' }));
fetch('/api/data')
.then(res => res.json())
.then(data => {
console.log(data); // { data: '12345' }
});
Mocking multiple fetch requests
This feature allows you to mock multiple fetch requests in sequence. Each call to fetch will return the next mocked response in the order they were defined.
const fetchMock = require('fetch-mock-jest');
fetchMock
.mockResponseOnce(JSON.stringify({ data: 'first' }))
.mockResponseOnce(JSON.stringify({ data: 'second' }));
fetch('/api/first')
.then(res => res.json())
.then(data => {
console.log(data); // { data: 'first' }
});
fetch('/api/second')
.then(res => res.json())
.then(data => {
console.log(data); // { data: 'second' }
});
Mocking fetch with different HTTP methods
This feature allows you to mock fetch requests based on different HTTP methods. In this example, a POST request to '/api/data' will return a specific response, while other methods will return a different response.
const fetchMock = require('fetch-mock-jest');
fetchMock.mockResponseOnce((req) => {
if (req.method === 'POST') {
return JSON.stringify({ message: 'Post request received' });
}
return JSON.stringify({ message: 'Other request' });
});
fetch('/api/data', { method: 'POST' })
.then(res => res.json())
.then(data => {
console.log(data); // { message: 'Post request received' }
});
Mocking fetch with different status codes
This feature allows you to mock fetch requests with different HTTP status codes. In this example, a fetch call to '/api/not-found' will return a 404 status, simulating a 'Not Found' error.
const fetchMock = require('fetch-mock-jest');
fetchMock.mockResponseOnce('', { status: 404 });
fetch('/api/not-found')
.then(res => {
if (!res.ok) {
throw new Error('Not Found');
}
return res.json();
})
.catch(error => {
console.error(error); // Error: Not Found
});
Other packages similar to fetch-mock-jest
jest-fetch-mock
jest-fetch-mock is a library that provides a similar functionality to fetch-mock-jest, allowing you to mock fetch calls in Jest tests. It offers a simple API to mock fetch responses and is well-integrated with Jest's mocking capabilities. Compared to fetch-mock-jest, jest-fetch-mock is more focused on Jest and provides a more straightforward API for common use cases.
nock
nock is a powerful HTTP mocking library for Node.js that allows you to intercept and mock HTTP requests. While it is not specifically designed for fetch, it can be used to mock fetch requests by intercepting the underlying HTTP calls. Nock provides a rich set of features for mocking and asserting HTTP requests, making it a versatile tool for testing HTTP interactions.
msw
msw (Mock Service Worker) is a library for mocking network requests in both browser and Node.js environments. It uses Service Workers to intercept and mock HTTP requests, providing a seamless way to test network interactions. MSW offers a declarative API for defining request handlers and supports a wide range of use cases, including fetch requests. Compared to fetch-mock-jest, MSW provides a more comprehensive solution for mocking network requests across different environments.
fetch-mock-jest
Wrapper around fetch-mock - a comprehensive, isomorphic mock for the fetch api - which provides an interface that is more idiomatic when working in jest.
The example at the bottom of this readme demonstrates the intuitive API, but shows off only a fraction of fetch-mock's functionality. 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
- isomorphic, and supports either a global fetch instance or a locally required instanceg
Requirements
fetch-mock-jest requires the following to run:
- Node.js 8+ for full feature operation
- Node.js 0.12+ with limitations
- npm (normally comes with Node.js)
- jest 25+ (may work with earlier versions, but untested)
- Either
- node-fetch when testing in Node.js. To allow users a choice over which version to use,
node-fetch
is not included as a dependency of fetch-mock
. - A browser that supports the
fetch
API either natively or via a polyfill/ponyfill
Installation
npm install -D fetch-mock-jest
global fetch
const fetchMock = require('fetch-mock-jest')
node-fetch
jest.mock('node-fetch', () => require('fetch-mock-jest').sandbox())
const fetchMock = require('node-fetch')
API
Setting up mocks
Please refer to the fetch-mock documentation and cheatsheet
All jest methods for configuring mock functions are disabled as fetch-mock's own methods should always be used
Inspecting mocks
All the built in jest function inspection assertions can be used, e.g. expect(fetchMock).toHaveBeenCalledWith('http://example.com')
.
fetchMock.mock.calls
and fetchMock.mock.results
are also exposed, giving access to manually inspect the calls.
The following custom jest expectation methods, proxying through to fetch-mock
's inspection methods are also available. They can all be prefixed with the .not
helper for negative assertions.
expect(fetchMock).toHaveFetched(filter, options)
expect(fetchMock).toHaveLastFetched(filter, options)
expect(fetchMock).toHaveNthFetched(n, filter, options)
expect(fetchMock).toHaveFetchedTimes(n, filter, options)
expect(fetchMock).toBeDone(filter)
Notes
filter
and options
are the same as those used by fetch-mock
's inspection methods- The obove methods can have
Fetched
replaced by any of the following verbs to scope to a particular method: + Got + Posted + Put + Deleted + FetchedHead + Patched
e.g. expect(fetchMock).toHaveLastPatched(filter, options)
Tearing down mocks
fetchMock.mockClear()
can be used to reset the call history
fetchMock.mockReset()
can be used to remove all configured mocks
Please report any bugs in resetting mocks on the issues board
Example
const fetchMock = require('fetch-mock-jest');
const userManager = require('../src/user-manager');
test(async () => {
const users = [{ name: 'bob' }];
fetchMock
.get('http://example.com/users', users)
.post('http://example.com/user', (url, options) => {
if (typeof options.body.name === 'string') {
users.push(options.body);
return 202;
}
return 400;
})
.patch(
{
url: 'http://example.com/user'
},
405
);
expect(await userManager.getAll()).toEqual([{ name: 'bob' }]);
expect(fetchMock).toHaveLastFetched('http://example.com/users
get');
await userManager.create({ name: true });
expect(fetchMock).toHaveLastFetched(
{
url: 'http://example.com/user',
body: { name: true }
},
'post'
);
expect(await userManager.getAll()).toEqual([{ name: 'bob' }]);
fetchMock.mockClear();
await userManager.create({ name: 'sarah' });
expect(fetchMock).toHaveLastFetched(
{
url: 'http://example.com/user',
body: { name: 'sarah' }
},
'post'
);
expect(await userManager.getAll()).toEqual([
{ name: 'bob' },
{ name: 'sarah' }
]);
fetchMock.mockReset();
});