Configure the network fixture in Playwright
mainTo use @msw/playwright, you should extend the Playwright test object with a network fixture. This is done using defineNetworkFixture.
Recommended setup pattern:
- Define a
handlersfixture containing your base MSW handlers. - Define a
networkfixture that usesdefineNetworkFixtureto wrap the Playwrightcontextandhandlers. - Call
network.enable()before the test runs andnetwork.disable()after it completes. - Set
{ auto: true }on the fixture so it is automatically initialized for every test.
// playwright.setup.ts
import { test as testBase } from '@playwright/test'
import { type AnyHandler } from 'msw'
import { defineNetworkFixture, type NetworkFixture } from '@msw/playwright'
import { handlers } from '../mocks/handlers.js'
interface Fixtures {
handlers: Array<AnyHandler>
network: NetworkFixture
}
const test = testBase.extend<Fixtures>({
// Initial list of the network handlers.
handlers: [handlers, { option: true }],
// A fixture you use to control the network in your tests.
network: [
async ({ context, handlers }, use) => {
const network = defineNetworkFixture({
context,
handlers,
})
await network.enable()
await use(network)
await network.disable()
},
{ auto: true },
],
})