Overview
Playwright’s network interception capabilities allow you to mock API responses, simulate network failures, and test edge cases without depending on external services.Basic Request Interception
Intercepting Requests
Usepage.route() to intercept and handle network requests:
Pattern Matching
Playwright supports multiple pattern types for route matching:Mocking API Responses
Mock with Static Data
Mock from File
Modifying Requests and Responses
Modify Request Headers
Modify Response
Simulating Network Conditions
Simulate Network Errors
Simulate Different Status Codes
1
Test 404 Not Found
2
Test 500 Server Error
3
Test 401 Unauthorized
Advanced Mocking Patterns
Mock Browser APIs
Mock browser APIs like Battery, Geolocation, or FileSystem usingpage.addInitScript():
Context-Wide Route Handlers
Apply routes at the context level for consistent mocking across all pages:Conditional Mocking
Unrouting
Remove route handlers when they’re no longer needed:Real-World Example
Here’s a complete example from the Playwright repository that tests GitHub API:Best Practices
- Mock at the right level: Mock at the context level for shared behavior, page level for specific tests
- Keep mocks realistic: Ensure mocked responses match the actual API structure
- Test error scenarios: Use mocking to test edge cases like network failures and error responses
- Avoid over-mocking: Only mock what’s necessary; let real requests through when possible
- Clean up routes: Unroute handlers when they’re no longer needed
