Mock fetch with MSW 2 in Vitest
Test fetch with MSW 2 in Vitest, override a handler for a 404, and fail requests that match no handler.
Your test swaps fetch for vi.fn() that returns an object with ok and json(). Then someone adds an accept header to the request, the code still works, and the test goes red.
What the hand-rolled mock checks
Save this function as user.js.
// user.js
export async function getUser(id) {
const res = await fetch(`https://api.example.com/users/${id}`, {
headers: { accept: 'application/json' },
})
if (!res.ok) throw new Error(`GET /users/${id} failed with ${res.status}`)
return res.json()
}If you use toHaveBeenCalledWith() to assert just the URL, the assertion fails as soon as the call includes an options object. A request handler can match on the method and URL and return a response with the same interface as a network response.
Answer the request with MSW
Mock Service Worker intercepts requests in the test process and answers them from handlers. Version 2 renamed rest to http, and a handler can return a standard Response or use MSW's HttpResponse.json() helper.
In a Node project with Vitest installed, set "type": "module" in package.json and install MSW with pnpm add -D msw@2. Save the handler as mocks.js.
import { http, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'
export const server = setupServer(
http.get('https://api.example.com/users/:id', ({ params }) => {
return HttpResponse.json({ id: Number(params.id), name: 'Ada' })
}),
)Save the test hooks as vitest.setup.js.
import { afterAll, afterEach, beforeAll } from 'vitest'
import { server } from './mocks.js'
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))
afterEach(() => server.resetHandlers())
afterAll(() => server.close())Add these settings to vitest.config.js so Vitest runs the setup file before the test file.
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
environment: 'node',
setupFiles: ['./vitest.setup.js'],
},
})Override one handler per test
Save this as user.test.js. In the second test, server.use puts the 404 handler in front of the default.
import { http, HttpResponse } from 'msw'
import { expect, test } from 'vitest'
import { server } from './mocks.js'
import { getUser } from './user.js'
test('reads a user', async () => {
expect(await getUser(7)).toEqual({ id: 7, name: 'Ada' })
})
test('throws on a 404', async () => {
server.use(
http.get('https://api.example.com/users/:id', () => new HttpResponse(null, { status: 404 })),
)
await expect(getUser(7)).rejects.toThrow('GET /users/7 failed with 404')
})Run pnpm exec vitest run user.test.js. Both tests pass. resetHandlers() drops the 404 handler after the second test so the next request to the same URL gets Ada again.
Make unmatched requests fail
By default MSW only warns about a request that no handler matches, and lets it go to the network. The setup above passes onUnhandledRequest: 'error'. Try fetching https://api.example.com/orders in a test. MSW logs the unmatched method and URL, blocks the network request, and the fetch promise rejects.
If the error names a request you meant to mock, compare its method and path with the handler. Check headers or query parameters inside the resolver when they affect the response.