YouTip LogoYouTip

Playwright Network Interception

Playwright's Network Interception is a very useful capability in automated testing and web scraping scenarios, allowing us to intercept, modify, and simulate network requests and responses. Playwright provides APIs such as `page.route()` and `page.on('request')` / `page.on('response')`, which can: * **Intercept Requests**: Decide whether to allow, modify URL/headers/body, or directly return mock responses. * **Monitor Requests/Responses**: View request URL, method, headers, response status code, response body, etc. * **Simulate Network Errors**: Block requests, return error codes, test the application's fault tolerance logic. Common application scenarios: * **Mock API**: Run frontend UI tests without backend APIs. * **Modify Requests**: For example, add tokens, test abnormal headers. * **Performance Debugging**: Count number of requests, response times. * **Error Injection**: Simulate server-side exceptions like 500/404. ### Intercept Requests: page.route() await page.route('**/api/todos', async route => { // Intercept matching requests console.log('Intercepted request:', route.request().url()); // 1. Allow request to proceed (continue request) await route.continue(); // 2. Modify request // await route.continue({ headers: { ...route.request().headers(), 'X-Test': 'true' } }); // 3. Return mock response // await route.fulfill({ // status: 200, // contentType: 'application/json', // body: JSON.stringify([{ id: 1, text: 'mock todo', done: false }]), // }); // 4. Abort request // await route.abort();}); **Parameter Description**: * `page.route(url, handler)`: Register an interceptor, `url` supports string, regex, or `**` wildcard. * `route.request()`: Get the request object. * `route.continue()`: Allow request to proceed, can modify method, headers, postData. * `route.fulfill(response)`: Directly return a fabricated response. * `route.abort()`: Abort the request, common error codes like `"failed"`, `"aborted"`, `"timedout"`. ### Monitor Requests and Responses // Monitor all requests page.on('request', req => { console.log(`➡️ Request: ${req.method()} ${req.url()}`);});// Monitor all responses page.on('response', async res => { console.log(`⬅️ Response: ${res.status()} ${res.url()}`);});// Get response bodyconst response = await page.waitForResponse('**/api/data'); console.log('Response content:', await response.text()); **Common Methods**: * `request.url()` / `request.method()` / `request.headers()` / `request.postData()` * `response.status()` / `response.headers()` / `response.text()` / `response.json()` ### Simulate Network Environment ## Example // Simulate network error await page.route('**/*.png', route => route.abort('failed')); // Simulate delay await page.route('**/api/**', async route =>{ await new Promise(r => setTimeout(r,2000)); await route.continue(); });

Complete Example: Mock API

import{ test, expect } from '@playwright/test'; test('Intercept and mock API', async ({ page })=>{ // Intercept /api/todos request and return fixed data await page.route('**/api/todos', async route =>{ await route.fulfill({ status:200, contentType:'application/json', body: JSON.stringify([ { id:1, text:'Playwright Learning', done:false}, { id:2, text:'Write Automated Tests', done:true}, ]), }); }); await page.goto('https://example-todo-app.com'); const items = await page.locator('.todo-item').allTextContents(); console.log('Loaded todo items:', items); // Assert UI displays mock data await expect(page.locator('.todo-item')).toHaveCount(2); await expect(page.locator('.todo-item').first()).toContainText('Playwright Learning'); }); * * * ## Network Interception Related APIs | API | Usage | Common Parameters/Description | | --- | --- | --- | | `page.route(url, handler)` | Register request interceptor | `url` can be string/regex/wildcard | | `route.request()` | Get request object | Returns `Request` | | `route.continue()` | Allow request to proceed, can modify | `{ method, headers, postData }` | | `route.fulfill(response)` | Return custom response | `{ status, headers, body, contentType }` | | `route.abort()` | Abort request | Common: `'failed'`, `'aborted'`, `'timedout'` | | `page.unroute(url, handler?)` | Remove interceptor rule | | | `page.on('request', cb)` | Monitor requests | | | `page.on('response', cb)` | Monitor responses | | | `request.url()/method()/headers()/postData()` | Request information | | | `response.status()/headers()/text()/json()` | Response information | | | `page.waitForResponse(urlOrPredicate)` | Wait for specific response | Can pass URL or function |
← Playwright Mobile TestPlaywright Test β†’