Introduction to jest-fetch-mock
Testing is a vital part of the software development lifecycle, and
jest-fetch-mock
makes testing with JavaScript’s fetch API much simpler. This
library allows you to easily mock responses, check the requests made, and troubleshoot your
tests faster.
Getting Started
To get started with jest-fetch-mock
, first you need to install it. You can do
this using npm or yarn:
npm install jest-fetch-mock
yarn add jest-fetch-mock
Basic Usage
To start using it in your Jest tests, you need to enable and configure it. Add the following
lines to your Jest setup file:
import { enableFetchMocks } from 'jest-fetch-mock';
enableFetchMocks();
Mocking `fetch` Calls
One of the primary use cases of jest-fetch-mock
is to mock fetch calls. You can
use the following APIs to mock different scenarios.
Mocking a Successful Response
To mock a successful response:
fetch.mockResponseOnce(JSON.stringify({ data: '12345' }));
fetch('/api/data').then(res => res.json()).then(data => {
expect(data.data).toBe('12345');
});
Mocking an Error Response
You can also mock an error response:
fetch.mockReject(() => Promise.reject('API is down'));
fetch('/api/data').catch(e => {
expect(e).toBe('API is down');
});
Advanced Usage By Scenarios
Multiple Mock Responses
You can set multiple mock responses to handle different calls in a sequence:
fetch
.mockResponseOnce(JSON.stringify({ data: 'first call' }))
.mockResponseOnce(JSON.stringify({ data: 'second call' }));
fetch('/api/first').then(res => res.json()).then(data => {
expect(data.data).toBe('first call');
});
fetch('/api/second').then(res => res.json()).then(data => {
expect(data.data).toBe('second call');
});
Resetting Mocks
After a test suite, you may need to reset the mocks to avoid state leak:
afterEach(() => {
fetch.resetMocks();
});
Real-world Example App with jest-fetch-mock
Let’s see an example of how you can integrate jest-fetch-mock
into a real-world
example app.
Application Code (app.js)
async function getData(url) {
const response = await fetch(url);
if (!response.ok) throw new Error('Network response was not ok');
return response.json();
}
export { getData };
Test Code (app.test.js)
import { getData } from './app';
import { enableFetchMocks } from 'jest-fetch-mock';
enableFetchMocks();
test('fetches successfully data from an API', async () => {
fetch.mockResponseOnce(JSON.stringify({ data: '12345' }));
const data = await getData('/api/data');
expect(data.data).toEqual('12345');
});
test('fetches erroneously data from an API', async () => {
fetch.mockReject(() => Promise.reject('API is down'));
await expect(getData('/api/data')).rejects.toThrow('API is down');
});
By following these examples, you can seamlessly integrate
jest-fetch-mock
into your Jest tests, making it easier to mock fetch calls and
validate the behavior of your application.
Happy Testing!