Skip to main content

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

Use page.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 using page.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

Use route.fetch(): When you need to modify responses, use route.fetch() to get the original response and then modify it, ensuring realistic behavior.
  • 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
Route handlers are called in reverse order of registration. The last registered handler is called first.

Troubleshooting

Routes not matching

Ensure your pattern matches the full URL:

CORS issues with mocked responses

Include proper CORS headers in mocked responses: