The page.route() method intercepts network requests. You can modify, fulfill, or abort them.
// Intercept and modify response
await page.route('**/api/users', async route => {
const response = await route.fetch(); // allow original request
const json = await response.json();
json.push({ id: 999, name: 'Mock User' });
await route.fulfill({ response, json });
});
// Abort specific requests
await page.route('**/analytics.js', route => route.abort());
await page.route('**/*.png', route => route.abort());
// Set session storage before navigating
await page.addInitScript(() => {
window.sessionStorage.setItem('auth_token', 'mock-token-123');
});
// Or after navigation
await page.evaluate(() => {
sessionStorage.setItem('theme', 'dark');
localStorage.setItem('preferences', JSON.stringify({ lang: 'en' }));
});
// Mock entire API response
await page.route('**/api/products', async route => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify([
{ id: 1, name: 'Mock Product', price: 99.99 }
])
});
});
// Network throttling simulation
await page.route('**/*', async route => {
await new Promise(r => setTimeout(r, 1000)); // add delay
await route.continue();
});
// Wait for specific response
const response = await page.waitForResponse('**/api/checkout');
const data = await response.json();
expect(data.success).toBe(true);
// Wait for network idle
await page.waitForLoadState('networkidle');