5 January, 2024 | 2 min read

How to Set Up MSW 2.0 in a React Project With Vite

Step 1: Install MSW

npm install msw --save-dev
npx msw init ./public

This will install MSW into our project and copy the worker script into the public directory.

Step 2: Set Up The Handlers

Create a file to define your request handlers.

mocks/handlers.ts
import { http, HttpResponse } from 'msw';
 
export const handlers = [
  // An example handler
  http.get('/user', () => {
    return HttpResponse.json({ name: 'John Maverick' });
  }),
];

Then, create a file to set up the handlers on the server and one for the browser. The browser file will be used when our app is running in the browser. The server file will be used by our tests.

mocks/node.ts
import { setupServer } from 'msw/node';
import { handlers } from './handlers';

export const server = setupServer(...handlers);
mocks/browser.ts
import { setupWorker } from 'msw/browser';
import { handlers } from './handlers';

export const worker = setupWorker(...handlers);

Step 3: Conditionally Enable Mocking

Update main.tsx to start the worker before rendering the app. We’ll only run this step in development so production is unaffection.

main.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import { App } from './App';
 
async function enableMocking() {
  if (process.env.NODE_ENV !== 'development') {
    return;
  }
 
  const { worker } = await import('./mocks/browser');
 
  // `worker.start()` returns a Promise that resolves
  // once the Service Worker is up and ready to intercept requests.
  return worker.start();
}
 
enableMocking().then(() => {
  ReactDOM.createRoot(document.getElementById('root')!).render(
    <React.StrictMode>
      <App />
    </React.StrictMode>
  )
});

Run the application in the browser, and you should see a confirmation message in the console in the Developer Tools.

[MSW] Mocking enabled.

Set Up MSW For Vitest Tests

In your test setup file, import and start the server.

vitest.setup.ts
import { server } from './mocks/node.js';

beforeAll(() => {
  server.listen();
});

afterEach(() => {
  server.resetHandlers();
});

afterAll(() => {
  server.close();
});

Follow me on Twitter or Bluesky to get updates on new posts.