Mock Service Worker (MSW) is a library that helps you mock HTTP requests in your tests. We can use it to define request handlers to respond different mock data mainly for testing.

Let’s see how to use MSW in browser environment.

Installation

Install msw package

bun install msw

Setup

Create a index.js which will be used to setup MSW and ship to browser.

import { HttpResponse, http } from "msw";
import { setupWorker } from "msw/browser";

// handlers
const userHandler = () => {
  return HttpResponse.json({
    id: "abc-123",
    firstName: "John",
    lastName: "Maverick",
  });
};

// handler list used by worker
const handlers = [http.get("/user", userHandler)];

// setup worker
const worker = setupWorker(...handlers);

worker.start();

We can build this bundle and use it in browser environment.

Build and run

This file can be built using bun itself

bun build index.js --outdir build

The build will create a index.js file in build directory, create an index.html file in the build directory with below content and open it in browser.

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    Hello There
    <script src="index.js"></script>
  </body>
</html>

We don’t need a server for this.

Fetching Data

We can use fetch API to fetch data from the server.

fetch("/user")
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error(error));

This will fetch the data from the server and log it in the console.

You can get the result from MSW

{id: 'abc-123', firstName: 'John', lastName: 'Maverick'}

Any request coming to /user via that page in browser, will be intercepted by MSW and the response will be the data we defined in the handler.