Answer
Network Interception with page.route()
page.route() intercepts HTTP/HTTPS requests matching a URL pattern and lets you mock, abort, or modify them.
Mock an API Response (Fulfill)
TypeScript
test('show product list with mocked API', async ({ page }) => {
// Intercept GET /api/products
await page.route('/api/products', async route => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify([
{ id: 1, name: 'Laptop', price: 999 },
{ id: 2, name: 'Mouse', price: 29 },
]),
});
});
await page.goto('/products');
await expect(page.locator('.product-card')).toHaveCount(2);
await expect(page.locator('.product-card').first()).toContainText('Laptop');
});
Block a Request (Abort)
TypeScript
// Block all image requests to speed up tests
await page.route('**/*.{png,jpg,jpeg,gif,svg}', route => route.abort());
// Block analytics tracking
await page.route('**/google-analytics.com/**', route => route.abort());
await page.route('**/hotjar.com/**', route => route.abort());
Modify Request and Pass Through
TypeScript
// Add auth header to every API call
await page.route('/api/**', async route => {
const headers = {
...route.request().headers(),
Authorization: 'Bearer test-token-123',
};
await route.continue({ headers });
});
Mock Error Responses
TypeScript
// Test how your app handles a 500 error
await page.route('/api/orders', route =>
route.fulfill({
status: 500,
body: JSON.stringify({ error: 'Internal Server Error' }),
})
);
await page.goto('/orders');
await expect(page.locator('.error-message')).toContainText('Something went wrong');
Mock Network Failure
TypeScript
// Simulate no network / timeout
await page.route('/api/data', route => route.abort('failed'));
Intercept Once
TypeScript
// Intercept only the FIRST matching request
await page.routeOnce('/api/user', route =>
route.fulfill({ json: { name: 'Test User', role: 'admin' } })
);
URL Pattern Matching
TypeScript
// Exact URL
await page.route('https://api.example.com/users', handler);
// Glob pattern
await page.route('**/api/**', handler);
await page.route('/api/products*', handler); // matches /api/products, /api/products?page=2
// Regex
await page.route(/\/api\/users\/\d+/, handler);
Inspect Request Details
TypeScript
await page.route('/api/**', async route => {
const request = route.request();
console.log('Method:', request.method()); // GET, POST, etc.
console.log('URL:', request.url());
console.log('Headers:', request.headers());
console.log('Body:', request.postData()); // POST body
await route.continue(); // Pass through unmodified
});
