Lesson 8 / 25
Network Mocking with page.route
Intercept, fulfil, modify, abort.
Controlling requests
page.route(urlPattern, handler) intercepts matching requests (glob, regex or predicate). In the handler call route.fulfill({ status, json }) to return a fake response, route.continue() to let it through (optionally with changed headers or body), route.abort() to simulate a network failure, or route.fetch() to get the real response and modify it before fulfilling. Routes are set up before the action that triggers the request. Use page.waitForResponse to wait for a specific call. Mocking makes edge cases (empty lists, server errors, slow responses) easy to test, but a fully mocked suite no longer proves that front end and back end agree, so keep some tests against the real API.
Fake, modify and fail requests
Three common uses.
import { test, expect } from '@playwright/test';
test('shows an empty state', async ({ page }) => {
await page.route('**/api/todos', (route) => route.fulfill({ status: 200, json: [] }));
await page.goto('/todos');
await expect(page.getByText('Nothing to do')).toBeVisible();
});
test('marks the first todo as overdue', async ({ page }) => {
await page.route('**/api/todos', async (route) => {
const response = await route.fetch();
const todos = await response.json();
todos[0].overdue = true;
await route.fulfill({ response, json: todos });
});
await page.goto('/todos');
await expect(page.getByText('Overdue')).toBeVisible();
});
test('handles a network failure', async ({ page }) => {
await page.route('**/api/todos', (route) => route.abort());
await page.goto('/todos');
await expect(page.getByRole('alert')).toContainText('Could not load');
});A stage manager feeding lines
The real actor (the backend) can be replaced by a stage manager who hands the app exactly the line the scene needs, including the awkward ones that rarely happen on opening night.
Quick check: Which call returns a fake response from a route handler?
- route.abort()
- route.continue()
- route.fulfill()
- page.goto()
Answer
route.fulfill() — continue passes through; abort fails the request.