Working with the network: page.route and mocks
With page.route a test decides what to answer to a request. Playwright sits between the page and the network, and the handler must call fulfill, continue, abort or fallback. A route intercepts only requests that start after it is registered, so it is declared before the action that triggers them. Mock errors, edge-case data and third-party services, and keep the happy path on the real backend.
Playwright · Network
The mock is registered, yet the page shows real backend data. What went wrong?
An "empty list" test registers a page.route that returns [], but the screen shows real cards from the backend. The backend is not to blame: the mock was registered after page.goto, and the request had already gone to the network. Below: how Playwright intercepts requests, what a handler must do, and where a mock hurts instead of helping.
How it works and why. The network is the best lever for controlling application state in an E2E test. Instead of preparing data on the backend and hoping it returns an empty list or an error, the test decides what to answer. Playwright sits between the page and the network: when the browser is about to send a request, it waits while Playwright asks the registered handlers in turn. Three things follow. A handler must make a decision, because the browser is waiting. Only requests that started after the registration are intercepted. And this is at browser level, so route sees any request of the page: fetch, XHR, images, scripts.
What happens to a request that route intercepted
Four actions on a request. page.route takes a URL pattern (glob, regular expression or function) and a handler. The handler calls one of: route.fulfill (own status, headers and body; the json parameter is handy), route.continue (let it through, changing headers, method or body), route.abort (abort with an error code) or route.fallback (hand it to the next handler).
// a mock: our status and body, the request never reaches the backend
await page.route('**/api/accounts', (route) =>
route.fulfill({ status: 200, json: [{ id: 1, name: 'Main', balance: 1200 }] }),
);
// an error response to see how the UI reacts
await page.route('**/api/transfers', (route) =>
route.fulfill({ status: 500, json: { error: 'Internal error' } }),
);
// cut off what the test does not need: faster and more stable
await page.route('**/*.{png,jpg,jpeg}', (route) => route.abort());
// let the request through, but change it
await page.route('**/api/reports', (route) =>
route.continue({ headers: { ...route.request().headers(), 'x-test-run': 'e2e' } }),
);
Example: the mock is there, but has no effect. The test has to show the empty state of the accounts list. It fails: the page shows accounts from the backend and there is no "No accounts yet" text. The mock looks right, so does the pattern. The cause is the order: by the time of the registration, page.goto had already waited for the load, and the request for accounts went out during it.
// before: the route comes after the navigation
await page.goto('/accounts');
await page.route('**/api/accounts', (route) => route.fulfill({ json: [] }));
await expect(page.getByText('No accounts yet')).toBeVisible();
The fix is the order of actions: first the route, then whatever triggers the request. The temptation to "add a wait" or a page.reload() after the mock also works, but it is a workaround: the test makes an extra request and hides the cause.
// after: first the route, then the action that triggers the request
await page.route('**/api/accounts', (route) => route.fulfill({ json: [] }));
await page.goto('/accounts');
await expect(page.getByText('No accounts yet')).toBeVisible();
route.fetch: change part of a real response. When you need not an invented response but a slightly spoiled real one, get it through route.fetch(), edit it and return it through fulfill({ response, json }). Status and headers stay real, while the UI is checked on edge data: an overdraft, a very long name.
await page.route('**/api/accounts', async (route) => {
const response = await route.fetch(); // the real response of the backend
const accounts = await response.json();
accounts[0].balance = -50; // an edge case: overdraft
accounts.push({ id: 99, name: 'A'.repeat(300), balance: 0 }); // a very long name
await route.fulfill({ response, json: accounts });
});
await page.goto('/accounts');
await expect(page.getByTestId('balance-1')).toHaveClass(/negative/);
States that are hard to get. A mock solves three classes of tasks: errors and slow responses (500, connection drop, spinner), empty and extreme data, and isolation from third-party services (payment gateway, SMS, analytics). For GraphQL all requests go to one URL, so the handler branches on operationName. The times option limits the number of triggers: handy for "the first request fails, the retry passes".
// a slow response: the spinner stays visible
await page.route('**/api/transactions*', async (route) => {
await new Promise((resolve) => setTimeout(resolve, 2000));
await route.fulfill({ json: [] });
});
// GraphQL: one URL for everything, so branch on the operation
await page.route('**/graphql', async (route) => {
const { operationName } = route.request().postDataJSON() ?? {};
if (operationName === 'Accounts') {
return route.fulfill({ json: { data: { accounts: [] } } });
}
return route.fallback(); // everything else goes to earlier handlers
});
// a one-off failure: the first call fails, the retry in the UI succeeds
await page.route('**/api/payments', (route) => route.abort('failed'), { times: 1 });
Scope. page.route works for one page, context.route for all pages of the context, including new tabs; if both apply, page routes take precedence. WebSocket has its own page.routeWebSocket. Requests that go through a Service Worker are not seen by a route until it is disabled with serviceWorkers: 'block'. How to record the mocks as a whole file is described in the HAR lesson.
Limits: what not to mock. A mock is a snapshot of the contract at the time of writing, and it goes stale silently: the backend changed a field, while the test with the mock stays green. So mock what is missing (errors, edge data, external services) and keep the main happy path on the real backend.
Two approaches to mocks in a suite
Everything mocked
The suite is fast and stable, but it checks the frontend only against its own inventions. A contract change on the backend goes unnoticed.
Mock only what is missing
The happy path hits the real backend and catches integration bugs. Mocks cover errors, empty and extreme states and third-party services.
Common mistakes.
page.routeafterpage.goto: requests that already went out are not affected by the mock.- A handler with a branch that calls none of
fulfill,continue,abortorfallback: the request hangs and the test times out. - A pattern that is too broad (
**/api/**): things that should go to the network get mocked. - A mock with no UI check: the test is green and it is unknown whether the mock applied.
- The whole E2E suite on mocks: contract changes go unnoticed.
Check yourself
A mock on **/api/accounts is registered in beforeEach, yet in one test the page still shows real data. What should you check first?
Answer
Whether that test has a page.goto or an action that triggers the request before the route is registered. Then: whether the pattern matches the full URL (a glob * does not cross /) and whether the request goes through a Service Worker.
A route handler has if (cond) route.fulfill(...) with no else. What happens when cond is false?
Answer
The request keeps waiting for a decision: the browser does not send it on its own. The test fails by timeout, not with an error about the mock. Every branch must call continue, fallback, fulfill or abort.
page.route intercepts a request and lets me substitute the response with fulfill, abort it with abort or let it through with continue. I declare the route before the action that triggers the request. Middle/Senior: For edge states (an empty list, a 500, a slow response) I use fulfill, and when only part of the real response must change I take route.fetch. I do not mock everything: the happy path stays on the real backend so integration bugs stay visible, and I type the mocks from the same schemas as the backend.