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 (or isomorphic-fetch)
notes
- When using isomorphic-fetch or node-fetch fetch should be added as a global
- fetch-mock doesn't declare fetch or Promise as dependencies; as you're testing
fetch
it's assumed you're already taking care of these globals
var fetchMock = require('fetch-mock');
fetchMock.registerRoute([
{
name: 'session',
matcher: 'https://sessionservice.host.com',
response: {
body: 'user-12345',
opts: {
headers: {
'x-status': 'unsubscribed'
},
status: 401
}
}
},
{
name: 'geo',
matcher: /^https\:\/\/geoservice\.host\.com/,
response: {
body: {
country: 'uk'
}
}
}
])
it('should do A', function () {
fetchMock.mock({
greed: 'none'
});
thingToTest.exec();
fetchMock.calls('session')
fetchMock.called('geo')
fetchMock.reset()
fetchMock.calls('session')
fetchMock.called('geo')
fetch.calledWith('thing')
fetchMock.restore();
})
describe('content', function () {
before(function () {
fetchMock.registerRoute('content', function (url, opts) {
return opts.headers.get('x-api-key') && url.test(/^https\:\/\/contentservice\.host\.com/);
}, {body: 'I am an article'});
});
after(function () {
fetchMock.unregisterRoute('content');
})
it('should do B', function () {
fetchMock.mock({
routes: ['session', 'content', {
name: 'enhanced-content',
matcher: /^https\:\/\/enhanced-contentservice\.host\.com/,
response: function (url, opts) {
return {body: 'enhanced-article-' + url.split('article-id/')[1]};
}
}]
});
thingToTest.exec();
fetchMock.calls('content')
fetchMock.called('enhanced-content')
fetchMock.restore();
})
it('should do C', function () {
fetchMock.mock({
responses: {
'session': 'invalid-user'
}
});
thingToTest.exec();
fetchMock.restore();
})
});