To set up MSW (Mock Service Worker) in your Jest + React Testing Library tests, follow these steps:
Install MSW and its dependencies:
sql
Copy code
npm install msw msw@next @testing-library/react-hooks --save-dev
Note: msw@next installs the latest beta version of MSW at the time of writing this.
Create a src/mocks/handlers.js file. This file will contain your mock server handlers. Here's an example:
php
Copy code
import { rest } from 'msw';
export const handlers = [
rest.get('/api/todos', (req, res, ctx) => {
return res(
ctx.status(200),
ctx.json([
{ id: 1, text: 'Buy milk' },
{ id: 2, text: 'Walk the dog' },
{ id: 3, text: 'Do laundry' },
]),
);
}),
];
Create a src/setupTests.js file. This file will configure your test environment to use MSW. Here's an example:
scss
Copy code
import { server } from './mocks/server';
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
Note: ./mocks/server is the path to your mock server file, which we will create in the next step.
Create a src/mocks/server.js file. This file will create and export a mock server instance. Here's an example:
javascript
Copy code
import { setupServer } from 'msw/node';
import { handlers } from './handlers';
export const server = setupServer(...handlers);
Use MSW in your tests. Here's an example:
javascript
Copy code
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders todos', async () => {
render(<App />);
const todo1 = await screen.findByText('Buy milk');
const todo2 = screen.getByText('Walk the dog');
const todo3 = screen.getByText('Do laundry');
expect(todo1).toBeInTheDocument();
expect(todo2).toBeInTheDocument();
expect(todo3).toBeInTheDocument();
});
That's it! Now your tests will use MSW to mock your API requests.