Playwright Network Interception: Mock APIs, Block Resources, and Control Every Request
Playwright’s page.route() gives you complete control over every network request your application makes. Mock APIs, block analytics, simulate errors, and test offline behavior — all without changing your application code.
🎭 Want to master this with real projects? Join the Playwright Automation Mastery course at The Testing Academy.
Contents
Basic API Mocking
test('mock API response', async ({ page }) => {
await page.route('**/api/users', route => {
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify([
{ id: 1, name: 'Test User', email: 'test@example.com' }
])
});
});
await page.goto('/users');
await expect(page.getByText('Test User')).toBeVisible();
});
Simulate Error Responses
test('handle 500 server error gracefully', async ({ page }) => {
await page.route('**/api/orders', route => {
route.fulfill({ status: 500, body: 'Internal Server Error' });
});
await page.goto('/orders');
await expect(page.getByText('Something went wrong')).toBeVisible();
await expect(page.getByRole('button', { name: 'Retry' })).toBeVisible();
});
🚀 Level Up Your Playwright
From locators to CI pipelines — build a production-grade Playwright + TypeScript framework step by step.
Block Third-Party Resources
test('block analytics and ads for faster tests', async ({ page }) => {
await page.route('**/*.{png,jpg,jpeg,gif,svg}', route => route.abort());
await page.route('**/analytics/**', route => route.abort());
await page.route('**/ads/**', route => route.abort());
await page.route('**google-analytics.com**', route => route.abort());
await page.goto('/dashboard'); // Loads 3x faster without images/analytics
});
Modify Requests in Flight
test('add custom headers to all API requests', async ({ page }) => {
await page.route('**/api/**', route => {
route.continue({
headers: {
...route.request().headers(),
'X-Test-Mode': 'true',
'X-Test-Id': 'test-123'
}
});
});
});
Wait for Specific API Responses
test('wait for API before asserting', async ({ page }) => {
const responsePromise = page.waitForResponse('**/api/search**');
await page.goto('/search');
await page.getByPlaceholder('Search').fill('playwright');
await page.getByRole('button', { name: 'Search' }).click();
const response = await responsePromise;
expect(response.status()).toBe(200);
const data = await response.json();
expect(data.results.length).toBeGreaterThan(0);
});
🎓 Master Playwright End to End
Join hundreds of SDETs building real automation frameworks. Lifetime access, hands-on projects, and a job-ready portfolio.
