Testing Requests In Jest With Msw
Topic | Source |
---|---|
๐งฉ React | [React Testing Library and Jest: The Complete Guide |
How to set up msw and use it to mock request handlers.
msw (Mock Service Worker) is a framework to create request handlers to mock data fetching tests.
It intercepts the configured requests and returns the response you give it without sending out the real request.
Manual Setup
To achieve this, you have to define the handlers and set up a server.
import { rest } from 'msw';
import { setupServer } from 'msw/node';
const handlers = [
rest.get('/getPerson', (req, res, ctx) => { // define the type of request (GET, POST,...) and the route, that you want to intercept
return res (
ctx.json({ //define the object to return
"id": 2,
"name": "John"
})
);
})
];
You will need to set up a testing server to handle the requests. You can use Jests lifecycle for this.
beforeAll(() => {
server.listen();
});
afterEach(() => {
server.resetHandlers();
});
afterAll(() => {
server.close();
});
msw works asynchronously, which means that you have to wait for the response before continuing testing. To achieve this, you can use one of React Testing Libary's functions that uses act()
under the hood:
screen.findBy...
screen.findAllBy...
waitFor
user.keyboard
user.click
Setup with server.js
It is generally a good approach, to put all of this setup into its' own file, by creating a server setup file:
server.js
import { setupServer } from 'msw/node';
import { rest } from 'msw';
export function createServer(handlerConfig) {
const handlers = handlerConfig.map((config) => {
return rest[config.method || 'get'](config.path, (req, res, ctx) => {
return res(ctx.json(config.res(req, res, ctx)));
});
});
const server = setupServer(...handlers);
beforeAll(() => {
server.listen();
});
afterEach(() => {
server.resetHandlers();
});
afterAll(() => {
server.close();
});
}
It can then be used like this:
import { createServer } from './test/server';
createServer([
{
path: `/getPerson`,
method: "post",
res: (req, res, ctx) => {
return {
"id": 2,
"name": "John"
}
},
}
]);