What is @types/fetch-mock?
@types/fetch-mock provides TypeScript type definitions for the fetch-mock library, which is used to mock HTTP requests in tests. This allows developers to simulate different responses from the fetch API, making it easier to test how their code handles various scenarios.
What are @types/fetch-mock's main functionalities?
Mocking a simple GET request
This feature allows you to mock a simple GET request. The code sample shows how to mock a GET request to '/api/data' and return a JSON object with sample data.
const fetchMock = require('fetch-mock');
fetchMock.get('/api/data', { data: 'sample data' });
fetch('/api/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 shows how to mock a POST request to '/api/submit' and return different responses based on the request body.
fetchMock.post('/api/submit', (url, options) => {
if (options.body === JSON.stringify({ name: 'test' })) {
return { status: 'success' };
} else {
return { status: 'error' };
}
});
fetch('/api/submit', { method: 'POST', body: JSON.stringify({ name: 'test' }) })
.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 shows how to mock a GET request to '/api/delayed' and return a response after a 1-second delay.
fetchMock.get('/api/delayed', new Promise(resolve => setTimeout(() => resolve({ data: 'delayed data' }), 1000)));
fetch('/api/delayed').then(response => response.json()).then(data => console.log(data));
Restoring fetch to its original state
This feature allows you to restore the fetch function to its original state after mocking. The code sample shows how to mock a GET request and then restore the fetch function.
fetchMock.get('/api/data', { data: 'sample data' });
fetchMock.restore();
fetch('/api/data').then(response => response.json()).then(data => console.log(data));
Other packages similar to @types/fetch-mock
nock
Nock is a HTTP mocking and expectations library for Node.js. It allows you to intercept HTTP requests and mock responses. Compared to fetch-mock, Nock is more focused on Node.js and provides a more extensive set of features for mocking HTTP requests.
msw
Mock Service Worker (MSW) is a library for mocking network requests in both browser and Node.js environments. It uses Service Worker API to intercept requests and provides a more modern approach to mocking compared to fetch-mock. MSW is particularly useful for testing in browser environments.
axios-mock-adapter
Axios Mock Adapter is a library that allows you to easily mock requests made with axios. It provides a simple API for defining mock responses for different HTTP methods. Compared to fetch-mock, axios-mock-adapter is specifically designed for use with the axios library.