Skip to content
tezvyn:

MSW: Mock APIs at the Network Layer

Source: mswjs.ioHardHow cards are made

MSW: Mock APIs at the Network Layer

Mock Service Worker intercepts API calls at the network level using a Service Worker, so your app makes real requests. Use it for consistent mocking in development, testing, and Storybook.

Why it exists

Traditional API mocking often involves patching fetch or specific data clients. This leads to brittle tests tied to implementation details and creates divergent mock definitions for different environments (unit tests, E2E tests, Storybook), causing drift and maintenance overhead.

The mental model

Think of MSW as a proxy server living inside your browser or Node.js process. Your application makes a real fetch('/api/user') call. Instead of going to the network, a Service Worker intercepts it and checks its own routing rules. If a handler matches, it returns a mocked response. Your app code is completely unaware it's not talking to a real server.

How it works

In the browser, MSW registers a Service Worker script that listens for fetch events at the network level. In Node.js, it uses a request interceptor to patch modules like http and https. You define request handlers that specify what to do for certain requests, like http.get('/posts', () => { return HttpResponse.json(...) }). When a request matches a handler, MSW returns the mocked response. If no handler matches, the request can proceed to the actual network.

When to use it

Use MSW to create a unified mocking strategy across your entire development lifecycle. It's ideal for three scenarios: first, developing UI features before the backend API is complete; second, writing stable integration and E2E tests that don't depend on a live backend; and third, populating tools like Storybook with realistic, dynamic data.

When not to use it

Avoid using MSW for true unit tests where you want to mock a specific function's return value without involving any network layer. The main footgun is using MSW to spy on requests for test assertions. Your tests should verify the user-facing outcome ("the user's name appeared on screen"), not the implementation detail ("a GET request was made to /user/123").

One canonical example

A common use case is handling application state during development. You can define a handler for a login endpoint: http.post('/login', () => { return HttpResponse.json({ user: { id: 'abc-123' }}) }). Now, any part of your app that calls the login function will receive a valid user object, allowing you to develop authenticated routes and features without needing a running backend. The same handler can then be reused in your Cypress or Playwright tests.

Interview question

In a browser environment, how does Mock Service Worker (MSW) enable mocking without altering the application's API calls?

  • a.It registers a Service Worker to intercept network requests before they leave the browser.Correct
  • b.It modifies the application's build process to inject mock data directly into API client libraries.
  • c.It sets up a local proxy server that reroutes API requests to mock endpoints.
  • d.It replaces the browser's native fetch and XMLHttpRequest with custom mock implementations.
Why?

The card states that in the browser, MSW registers a Service Worker script that listens for fetch events at the network level, allowing the app to make real requests. Option D describes a traditional mocking approach that MSW aims to avoid, as it doesn't directly patch global objects but intercepts at a lower network layer.

Just read this? Test yourself on what you have been reading.

Read the original → mswjs.io

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Every open role lists the topics its interview covers, so you can prepare for the real thing rather than guessing.

See open roles