Introduction to jest-fetch-mock
In modern web development, handling HTTP requests in testing is crucial. `jest-fetch-mock` is a powerful tool that allows you to easily mock fetch calls in your tests, making it easier to isolate and test various components of your application. This guide will introduce you to `jest-fetch-mock`, explain its dozens of useful APIs, and provide code snippets to help you get started quickly.
Getting Started
First, you need to install the `jest-fetch-mock` package:
npm install jest-fetch-mock --save-dev
Basic Mocking
To start using `jest-fetch-mock`, you need to configure Jest:
require('jest-fetch-mock').enableMocks();
You can now mock a basic fetch request like this:
fetchMock.mockResponseOnce(JSON.stringify({ data: '12345' }));
Mocking Multiple Calls
To handle multiple fetch requests, use:
fetchMock.mockResponses( [JSON.stringify({ data: '12345' }), { status: 200 }], [JSON.stringify({ error: 'Unauthorized' }), { status: 403 }] );
Conditional Mocking
You can mock different responses based on request conditions:
fetchMock.mockResponse((req) => { if (req.url.endsWith('/success')) { return Promise.resolve(JSON.stringify({ status: 'ok' })); } else { return Promise.reject(new Error('failed')); } });
Resetting Mocks
To reset all mocks, use:
fetchMock.resetMocks();
Mocking with Headers
Further customize your mock response with headers:
fetchMock.mockResponseOnce( JSON.stringify({ data: '12345' }), { headers: { 'content-type': 'application/json' }} );
Real-World Application Example
Below is an example of a simple React application using `jest-fetch-mock`:
// MyComponent.jsx import React, { useEffect, useState } from 'react'; function MyComponent() { const [data, setData] = useState(null); useEffect(() => { fetch('/api/data') .then(response => response.json()) .then(data => setData(data)); }, []); return ( <div> {data ? <p>{data}</p> : <p>Loading...</p>} </div> ); } export default MyComponent;
And the test file:
// MyComponent.test.jsx import React from 'react'; import { render, waitFor } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import MyComponent from './MyComponent'; beforeEach(() => { fetchMock.resetMocks(); }); test('displays data after fetch', async () => { fetchMock.mockResponseOnce(JSON.stringify({ data: '12345' })); const { getByText } = render(<MyComponent />); await waitFor(() => getByText('12345')); expect(getByText('12345')).toBeInTheDocument(); });
By following this guide, you should now have a solid understanding of how to use `jest-fetch-mock` to efficiently mock fetch calls in your tests. Happy coding!
Hash: 777229d8fc366f7d4a977fd2dab92cd88467c64a2b4cf1fc0ff681d568b2cab0