Community TypeScript Snippet

Why I Stopped Mocking `fetch` and Reached for MSW

The two-handler MSW setup I drop into every Vitest project. Pattern-matched URL routing, typed JSON responses, and per-test overrides without re-importing the server.

Why I Stopped Mocking `fetch` and Reached for MSW

The two-handler MSW setup I drop into every Vitest project. Pattern-matched URL routing, typed JSON responses, and per-test overrides without re-importing the server.

TypeScript
Frontend
3 snippets
testing
http
code-template
utility
ezb1981

By @ezb1981

May 8, 2026

·

Updated May 18, 2026

1,029 views

26

4.4 (9)

This is the pattern I see in most codebases: globalThis.fetch = jest.fn(...) and a manual response table. It works for one test, then someone forgets to reset between tests and you get bleed-through that only shows up in CI when the test order shuffles. The deeper issue is that you are mocking the wrong layer: your code uses fetch, axios, ky, or a generated SDK, and each one has slightly different semantics, so the mock has to be re-implemented per library. Stage two shows the pivot.