Mocking fetch & HTTP Requests in Vitest
From the Vitest cheat sheet · Globals, Env & Network · verified Nov 2026
Mocking fetch & HTTP Requests
Stub fetch for quick unit tests or intercept real requests with MSW
typescript
const fetchMock = vi.fn().mockResolvedValue(
new Response(JSON.stringify({ id: 1 }), { status: 200 }),
)
vi.stubGlobal('fetch', fetchMock)
await getUser(1)
expect(fetchMock).toHaveBeenCalledWith('https://api.example.com/users/1')🎯 MSW intercepts at the network level, so app code stays untouched
📌 MSW 3 renamed onUnhandledRequest to onUnhandledFrame
💡 server.use() overrides a handler for one test; reset in afterEach
⚡ For one-off unit tests, vi.stubGlobal('fetch', vi.fn()) is enough
fetchmswhttpnetwork
Continue with Vitest
Save the full cheat sheet or work through every related task.