Network Interception and Mocking in Playwright
Network interception and mocking are powerful features in Playwright that allow you to capture, modify, or simulate HTTP requests and responses during test execution. These capabilities are especially useful when testing edge cases, error handling, or simulating unreliable network conditions.
1. Capturing and Mocking HTTP Requests
Playwright’s route
method provides a flexible way to intercept HTTP requests before they reach the server. This allows you to mock responses, bypass network calls, or simulate specific scenarios without modifying the backend.
1.1 Intercepting HTTP Requests
To intercept requests, you can use the page.route()
method, which provides a callback to handle the request. This allows you to inspect the request’s URL, headers, and body and decide how to respond.
Example:
import { chromium } from 'playwright';
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.route('**/api/data', async (route) => {
console.log(`Intercepted request: ${route.request().url()}`);
await…