How to setup MSW in a React project using Vite
Tl;dr: Sample Project with React, Vite and MSW
First of all, you must have a Vite project. After that, you can install MSW with the following command:
npm install msw --save-dev
Setup MSW
To setup MSW, you'll create a file called handlers.ts
in the src
directory or in any other fold. This file will contain all of your handlers:
import { rest } from "msw";
// This handler will intercept any rest request in your project.
export const handlers = [];
Example:
import { rest } from "msw";
export const handlers = [
rest.get(
"https://https://jsonplaceholder.typicode.com/todos/1",
(_, res, ctx) => {
return res(
ctx.status(200),
ctx.json({
userId: 1,
id: 1,
title: "delectus aut autem",
completed: false,
})
);
}
),
];
After that, two new files will be created, one that will intercept the browser request, and other, that will intercept the Node request. For example:
import { setupServer } from "msw/node";
import { handlers } from "./handlers";
export const server = setupServer(...handlers);
import { setupWorker } from "msw";
import { handlers } from "./handlers";
export const worker = setupWorker(...handlers);
Setup the application
With the files created, you can now setup the application. First, you'll import the browser.ts
in the entrypoint file of your project. For example:
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { App } from "@/App"; // The main component of the application.
// The root element where React will be mounted.
const root = createRoot(document.getElementById("root") as HTMLElement);
if (import.meta.env.MODE === "development") {
// When development, setup the MSW.
// import the worker (under the browser.ts file)
import("./browser")
.then(({ worker }) => {
// Start the worker.
worker.start();
})
.then(() => {
// Render the application.
root.render(
<StrictMode>
<App />
</StrictMode>
);
});
} else {
// Render the application in production without the MSW.
root.render(
<StrictMode>
<App />
</StrictMode>
);
}
Setup the tests
In your test setup, import the server.ts
, and start the server. For example:
import { server } from "./server";
beforeAll(() => {
server.listen({ onUnhandledRequest: "error" });
});
afterEach(() => {
server.resetHandlers();
});
afterAll(() => {
server.close();
});
Project example
You can find a project example in the following repository: https://github.com/raisiqueira/example-msw-vite/