How to setup MSW in a React project using Vite
Published Jan 9, 2023
⋅
Updated Nov 4, 2024
⋅
1 minutes read
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:
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:
Example:
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:
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:
Setup the tests
In your test setup, import the server.ts
, and start the server. For example:
Project example
You can find a project example in the following repository: https://github.com/raisiqueira/example-msw-vite/
Useful links