Skip to content
matthewcm.dev

    ↑ ↓ move · ↵ open · tab scopeopen graph →

    Stop Mocking Fetch

    Mocking fetch or your own API modules couples tests to implementation and quietly re-implements your backend in every test file. Mock the network boundary instead.

    Evergreentended planted 1 min read
    On this page

    Kent C. Dodds wrote a post called Stop mocking fetch, and it changed how I write frontend tests. His line that stuck with me: mocking fetch means you end up re-implementing your entire backend… everywhere in your tests.

    What goes wrong

    // brittle: tied to how the code fetches, not what the user sees
    global.fetch = jest.fn().mockResolvedValue({ json: () => ({ id: 1, name: "Push" }) });
    jest.mock("./api/workouts");
    • Every test hand-builds fake responses, often slightly differently.
    • Refactor the data layer — switch fetch for a client library, add a transform — and tests break even though nothing a user sees has changed.
    • Your parsing and error handling never actually run, so the bugs that live there go untested.

    The alternative

    Mock at the network boundary with MSW. Define server handlers once, for the whole API, as if the app were talking to a real backend. They aren’t specific to any one test.

    • Realistic. Real requests leave your code; real responses come back. Your data layer is exercised end to end.
    • Unified. The same handlers work in Node tests, in the browser and in Storybook.
    • Isolated. Override a handler in a single test for an error case; reset afterwards.
    • Refactor-proof. Tests describe behaviour, so you can rework internals with confidence.

    Bonus uses

    The same handlers let you run the app locally against fake data, which helps when:

    1. the endpoint isn’t ready yet,
    2. the endpoint is broken,
    3. your connection is slow or non-existent.

    The caveat

    Mocks can drift from reality. I still want a handful of end-to-end tests hitting real APIs, and contract checks where a spec exists. Mocking the network makes your tests honest about your code; it can’t make them honest about someone else’s.

    In practice

    Switching a team’s tests to network-level mocks made them quicker to write and noticeably more stable through refactors. It was the backbone of A Testing Strategy Teams Actually Adopted and sits at the centre of my React Testing Strategy.

    • #testing
    • #mocking
    • #msw
    • #integration-tests

    ↪ Links to (3)