Jest · Unit tests that survive refactors

How do you use MSW with Jest?

HardmswnetworkintegrationUpdated Oct 2026
Quiz this track

Short answer

MSW intercepts requests with handlers at the network layer, so application code runs unmodified. Start the server in beforeAll, reset handlers between tests, and close it in afterAll.

Mock Service Worker installs an interceptor rather than replacing fetch in your code. Handlers describe responses by method and URL. The component and data layer still call the real fetch, so status handling, headers and parsing are exercised.

ts
import { setupServer } from "msw/node";
import { http, HttpResponse } from "msw";

const server = setupServer(
  http.get("/api/users/:id", ({ params }) =>
    HttpResponse.json({ id: params.id, name: "Asha" }),
  ),
);

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

test("renders the user", async () => {
  render(<Profile id="u1" />);
  expect(await screen.findByText("Asha")).toBeInTheDocument();
});

Why use MSW here

  • Handlers are reusable across unit, integration and browser tests
  • Requests are matched by URL and method, not call order
  • Per-test overrides use server.use without leaking to other tests
  • The same handlers can run in a real browser through the worker

resetHandlers removes overrides added with server.use but keeps the base handlers. That makes it the right cleanup between tests. If you need to assert that a request was made, inspect the request in a handler or use a spy on the client, rather than relying on call order.

MSW intercepts requests made through supported APIs in the same process. Requests made by a separate process, such as a real backend in another container, are outside its interception. For those, use a test server or contract tests.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1What is the difference between resetHandlers and restoreHandlers?
  2. 2How do you override a handler for a single test?
  3. 3Can MSW intercept requests from another process?
  4. 4How do you assert on the request body with MSW?

Say it in the interview

MSW intercepts at the network layer, so my application code and data layer run unchanged. I start the server once, reset handlers after each test so overrides do not leak, and close it at the end. Per-test behaviour comes from server.use. I like it because the same handlers can be reused in the browser, which keeps mocks closer to reality than stubbing fetch in each file.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Jest mock interview and get scored feedback on depth, clarity and confidence.