MSW fixture
Compose a test-scoped MSW 2 or MSW 3 server with your Vitest test API
withMsw creates a fixture definition for Vitest's test.extend. It adds a test-scoped
MSW server without replacing your test API. Choose the entrypoint
that matches your installed MSW major version.
See the API reference for each version's options and defaults.
Create a shared test API
Define default handlers and pass the fixture to test.extend:
import { withMsw } from "@octopus-energy/vitest/msw/v2";
import { http, HttpResponse } from "msw";
import { test as base } from "vitest";
export const test = base.extend(
withMsw({
defaultHandlers: [
http.get("https://example.test/user", () => HttpResponse.json({ name: "Ada" })),
],
}),
);Both entrypoints export withMsw and the types MswOptions and MswFixture.
base.extend(withMsw()) uses defaultHandlers: [] and the same strict policies.
Use the fixture
Import the shared test and request msw in the test callback. The server starts only
for tests that request the fixture. Usage is the same for both versions:
import { http, HttpResponse } from "msw";
import { expect } from "vitest";
import { test } from "./fixtures.ts";
test("loads a user", async ({ msw }) => {
const response = await fetch("https://example.test/user");
expect(await response.json()).toEqual({ name: "Ada" });
msw.use(http.get("https://example.test/user", () => new HttpResponse(null, { status: 503 })));
expect((await fetch("https://example.test/user")).status).toBe(503);
msw.resetHandlers();
expect(await (await fetch("https://example.test/user")).json()).toEqual({
name: "Ada",
});
});msw.use(...) prepends handlers for the current test, giving them priority over existing
handlers. Default handlers remain available for other requests. msw.resetHandlers() removes
these additions and restores defaultHandlers.