How does Playwright handle network interception?
Your course list page calls /api/courses. You want to test three things: the list renders, an empty list shows a friendly message, and a server error shows an error banner. Waiting for the real backend to be in each of those states is slow and unreliable. Playwright lets the test sit between the page and the network and decide what each request gets back. That is network interception, and it is done with route().
The three things a route handler can do
You register a URL pattern with page.route() (one tab) or context.route() (every tab in the context). For each matching request, your handler must choose one action:
| Call | Effect |
|---|---|
route.fulfill() | Answer the request yourself: status, headers, body or json. The real server is never contacted. |
route.continue() | Send the request on, optionally with changed headers, method, URL or post data. |
route.abort() | Fail the request, as if the network dropped it. |
Two helpers sit on top: route.fetch() performs the real request so you can edit the response before fulfilling, and route.fallback() passes the request to the next matching handler.
Example: mock, error and block
// tests/courses.spec.ts
import { test, expect } from '@playwright/test';
test('renders courses from a mocked API', async ({ page }) => {
await page.route('**/api/courses', route =>
route.fulfill({ json: [{ name: 'Playwright Basics' }, { name: 'API Testing' }] })
);
await page.goto('/courses');
await expect(page.getByRole('listitem')).toHaveText(['Playwright Basics', 'API Testing']);
});
test('shows an error when the API fails', async ({ page }) => {
await page.route('**/api/courses', route =>
route.fulfill({ status: 500, body: 'Internal Server Error' })
);
await page.goto('/courses');
await expect(page.getByText('Something went wrong')).toBeVisible();
});
test('loads without images', async ({ page }) => {
await page.route('**/*.{png,jpg,jpeg,webp}', route => route.abort());
await page.goto('/courses');
});
The routes must be registered before goto(), otherwise the first requests have already gone out. The labels and messages are placeholders for your app.
Edit a real response
Sometimes you want the real data plus one extra item, for example to test how the page handles a very long course name:
await page.route('**/api/courses', async route => {
const response = await route.fetch(); // real request
const json = await response.json();
json.push({ name: 'A course with a very long title that should wrap neatly on a phone' });
await route.fulfill({ response, json }); // real headers, edited body
});
Watching traffic without changing it
Not every test needs to change traffic. To assert that the page called the right endpoint, wait for it:
const responsePromise = page.waitForResponse('**/api/courses');
await page.getByRole('button', { name: 'Refresh' }).click();
const response = await responsePromise;
expect(response.status()).toBe(200);
For logging, page.on('request') and page.on('response') fire for every request. To replay a whole recorded session, Playwright can serve responses from a HAR file; see what a HAR file is and how Playwright uses it.
Gotchas
- Handler order. When two routes match the same URL, the one registered last runs first. Call
route.fallback()in it to hand the request to the earlier one. - Pattern does not match.
'/api/courses'is not the same as'**/api/courses'. Use the glob, a RegExp, or a function that receives aURL. - Query strings.
'**/api/courses'does not match/api/courses?page=2. Add*at the end or use a RegExp. - Service workers. Requests made by a service worker may bypass your routes. Set
serviceWorkers: 'block'inusewhen you mock an app that registers one. - Forgotten handlers. Remove a route with
page.unroute()when a later step needs the real backend.
Related: more on page.route(), simulating slow networks and monitoring network performance.
Want to master Playwright hands-on?
Join Uncodemy's Playwright Automation Testing Course in Noida — Dedicated Placement Support.
Explore the Course →