Network mocking and auth state
page.route() — intercepting and controlling network requests:
- Mock responses:
route.fulfill({ status: 500, json: {...} })— error states without the backend - Modification: pass the request through, alter the response
- Blocking:
route.abort()— e.g. cut analytics/ads requests to speed tests up
Use cases: 500/timeout error states, empty lists, rare data conditions, simulating third-party services (payment providers).
storageState — logging in once: a setup project logs in and saves storageState.json (cookies + localStorage); all tests start with that state. Result: 5-10 seconds saved per test + a single-point dependency on the login page.
The golden rule of mocking: never mock the thing under test. If you're testing the payment flow, mocking the payment API makes the test meaningless; but mocking the payment provider's slowness on an unrelated page is right. Mocks isolate dependencies — they don't replace the behaviour being verified.
📚 Sources and documentation
- Mock APIsofficialplaywright.dev
- Authenticationofficialplaywright.dev