What are the best practices for handling network interception, route mocking, and API response modification in Playwright?
Asked by The SDET Playbook
Asked Sep 28, 2026Viewed 0 times
What are the best practices for handling network interception, route mocking, and API response modification in Playwright?
Asked by The SDET Playbook
Sign in to answer and to vote.
page.route() intercepts matching requests so a test can control what the page receives. Three patterns cover most needs.
Return a fixed response, for example to test an error state:
test('shows an error when the profile fails to load', async ({ page }) => {
await page.route('**/api/v1/user/profile', (route) =>
route.fulfill({ status: 500, json: { error: 'Internal Server Error' } }),
);
await page.goto('/profile');
await expect(page.getByRole('alert')).toContainText('Something went wrong');
});
Modify a real response, keeping the rest of it:
await page.route('**/api/v1/cart', async (route) => {
const response = await route.fetch();
const cart = await response.json();
await route.fulfill({ response, json: { ...cart, items: [] } });
});
Pass a request on unchanged with route.continue(), or with route.fallback() when another handler registered earlier should get the chance to handle it.
Mock what you don't control or can't make fail on demand: third-party services, error responses, slow responses. Keep at least some tests against the real backend, because a mock can drift from the real API. Register routes before the navigation that triggers the request, and use context.route() when a whole context, including popups, should see the same mock.
Sources: Playwright mock APIs, Playwright network