98 / 139 · 13 Browser Automation with Playwright · Network Mocking and API Testing← prev⊞ allnext →☰ Read as one page
11.2Request Interception
page.route() intercepts requests matching a URL pattern and lets you fulfill, abort, or modify them.
Mocking API Responses
test('shows empty state when no products exist', async ({ page }) => {
// Mock the API to return an empty array
await page.route('**/api/products', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify([]),
});
});
await page.goto('/products');
await expect(page.getByText('No products found')).toBeVisible();
});
test('handles server error gracefully', async ({ page }) => {
await page.route('**/api/products', async (route) => {
await route.fulfill({ status: 500 });
});
await page.goto('/products');
await expect(page.getByRole('alert')).toHaveText(/something went wrong/i);
});
Modifying Requests
// Add an auth header to all API requests
await page.route('**/api/**', async (route) => {
await route.continue({
headers: {
...route.request().headers(),
'Authorization': 'Bearer test-token',
},
});
});
// Modify response data (e.g., inject a test flag)
await page.route('**/api/config', async (route) => {
const response = await route.fetch();
const json = await response.json();
json.featureFlags.newCheckout = true;
await route.fulfill({ response, body: JSON.stringify(json) });
});
Aborting Requests
// Block analytics and tracking in tests
await page.route('**/{analytics,tracking}/**', (route) => route.abort());
// Block images to speed up tests
await page.route('**/*.{png,jpg,jpeg,svg}', (route) => route.abort());