Intercept Requests
Intercepting requests lets you mock responses, inspect payloads, block trackers, and simulate failures — page.route is the primary interception API.
Interception Patterns
Match URLs with globs or regex. In the handler, inspect route.request() for method, headers, postData. Fulfill, continue, or abort based on logic.
Use page.waitForRequest to assert the app sent expected JSON body when user submits a form.
let capturedBody: string | undefined;
await page.route('**/api/checkout', async route => {
capturedBody = route.request().postData() ?? undefined;
await route.fulfill({ status: 200, body: '{"ok":true}' });
});
await page.getByRole('button', { name: 'Pay' }).click();
expect(JSON.parse(capturedBody!).items).toHaveLength(2);
Inspect postData before fulfilling mock response.
route.request() Details
const req = route.request();
req.method()
req.url()
req.headers()
req.postData()
req.postDataJSON() // parse JSON body
- Fulfill short-circuits — request never reaches server.
- Continue sends to network — useful with route.fetch patch.
- Abort simulates blocked or failed requests.
- context.route applies to all pages in context.
Intercept Recipes
Common interception tasks.
| Task | Technique |
| Assert POST body | Capture postData in route handler |
| Block ads | route.abort() on ad domains |
| Add header | route.continue({ headers }) |
| Redirect API | Fulfill with different JSON per test |
| Wait for request | waitForRequest predicate on URL+method |
| Remove route | page.unroute(url, handler) |
Intercepting GraphQL
await page.route('**/graphql', async route => {
const op = route.request().postDataJSON()?.operationName;
if (op === 'GetUser') {
await route.fulfill({ body: JSON.stringify({ data: { user: mock } }) });
} else {
await route.continue();
}
});
Predicate-Based Routing
Pass a function (route, request) => boolean to page.route when URL globs are insufficient — e.g. intercept only POST requests to /api.
Common Mistakes
- Intercept registered after request already fired.
- postDataJSON on non-JSON body throws — guard with try/catch.
- Over-broad
**/* route slowing every test. - Not unrouteing causing cross-test pollution.
Key Takeaways
- page.route intercepts before network completes.
- Inspect request payloads for behavior verification.
- Fulfill, continue, or abort per handler logic.
- GraphQL needs operationName filtering in handler.
Pro Tip
Keep reusable mock handlers in tests/mocks/handlers.ts — import into specs to avoid 30-line route blocks inline.