Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 1 min read

MSW for Beginners: Mock Your API Without a Backend

Every frontend developer has hit this wall: the backend is not ready, but the UI needs data. MSW, Mock Service Worker, solves it by intercepting network requests in the browser and returning mock responses β€” your app cod

Every frontend developer has hit this wall: the backend is not ready, but the UI needs data. MSW, Mock Service Worker, solves it by intercepting network requests in the browser and returning mock responses β€” your app code never knows the difference.
You define handlers that describe what each endpoint should return:

import { http, HttpResponse } from "msw";

export const handlers = [
  http.get("/api/users", () => {
    return HttpResponse.json([
      { id: 1, name: "Arhan" },
      { id: 2, name: "Priya" },
    ]);
  }),
];

Then you start a worker in development:

import { setupWorker } from "msw/browser";
import { handlers } from "./handlers";

await setupWorker(...handlers).start();

Your components call fetch("/api/users") exactly as they would in production, and the worker answers. When the real backend arrives, you stop the worker and nothing in your components changes. MSW also works in Node for tests, so the same handlers can power your test suite.
MSW is for you if you build frontends against APIs that are slow, unfinished, or flaky, and if you want tests that do not depend on a running server. It is especially good for error states: a handler can return a 500 or a slow response on demand, which is hard to reproduce against a real API.
But know its limits. MSW only mocks the network layer β€” it does not test your real backend. Mocks can drift from the real API, so you still need integration tests. And setting up the service worker file takes a few steps the first time.
Start today: take one page that fetches data, write one handler for its endpoint, and load the page with the worker running. Then add a second handler that returns an error, and check that your error UI actually shows up.

πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.