Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Workflow:Microsoft Playwright Network mocking and interception

From Leeroopedia
Knowledge Sources
Domains Network_Mocking, Test_Automation, API_Interception
Last Updated 2026-02-11 22:00 GMT

Overview

End-to-end process for intercepting, modifying, and mocking network requests and browser APIs in Playwright tests to control test environment behavior.

Description

This workflow covers Playwright's network interception and browser API mocking capabilities. Network interception allows tests to modify, block, or replace HTTP requests and responses in flight using the page.route() API. Browser API mocking uses page.addInitScript() to inject custom implementations of browser APIs (e.g., Battery API, File System API, Geolocation) before any page code executes. Together, these features enable fully deterministic testing by eliminating external dependencies, simulating error conditions, and controlling the data that tests see.

Usage

Execute this workflow when tests depend on external APIs that are unreliable, slow, or have rate limits; when you need to test error handling for failed network requests; when testing features that rely on browser APIs not available in test environments (e.g., Battery, USB, Bluetooth); or when you need to ensure consistent test data regardless of backend state.

Execution Steps

Step 1: Identify interception targets

Determine which network requests or browser APIs need to be mocked for the test scenario. Review the application's network activity to identify API endpoints that should return controlled data, and identify browser APIs that need custom implementations.

Key considerations:

  • Use browser DevTools or Playwright's network logging to identify target URLs
  • Decide between full mocking (no real request) and modification (alter request/response)
  • Identify browser APIs used by the application that are unavailable in headless mode
  • Consider which responses need to vary between test cases

Step 2: Set up network route handlers

Register route handlers using page.route() or context.route() to intercept matching requests. Route handlers receive a Route object that can fulfill the request with custom data, continue to the server with modifications, or abort the request entirely.

Key considerations:

  • Use URL patterns or regex to match requests: page.route('**/api/users', handler)
  • route.fulfill() responds with custom status, headers, and body without hitting the server
  • route.continue() forwards the request to the server, optionally modifying headers or URL
  • route.abort() blocks the request entirely (useful for testing offline behavior)
  • Context-level routes apply to all pages in the context

Step 3: Inject browser API mocks

Use page.addInitScript() to inject JavaScript that runs before any page scripts. This allows replacing browser API implementations with custom mock objects that return controlled values. The mock implementations should match the API interface that application code expects.

Key considerations:

  • addInitScript() runs in the browser context before any application code
  • Mock objects should implement the same interface as the real API
  • Use page.exposeFunction() to bridge Node.js functions into the browser context
  • Mocked APIs can emit events to simulate real-time changes (e.g., battery level changes)
  • State can be managed from the test by calling exposed functions

Step 4: Implement response fixtures

Create response fixture data (JSON files, mock objects, or inline data) that route handlers return. Organize fixtures to be reusable across tests and easy to maintain. For HAR-based mocking, record real API responses to a HAR file and replay them in tests.

Key considerations:

  • Store fixture data in separate files for maintainability
  • Use page.routeFromHAR() to replay recorded network traffic from HAR files
  • HAR files can be recorded with --save-har CLI flag or context.routeFromHAR()
  • Fixtures should cover both success and error response scenarios

Step 5: Verify interactions and assertions

Write assertions that verify the application correctly handles mocked responses and API data. Verify that the UI renders the expected content, handles errors gracefully, and responds appropriately to simulated state changes.

Key considerations:

  • Assert UI state after mocked data is loaded
  • Test error handling by fulfilling routes with error status codes
  • Verify that mocked events (e.g., battery level change) trigger appropriate UI updates
  • Use page.waitForResponse() to synchronize on specific network responses
  • Verify that specific requests were made using page.waitForRequest()

Execution Diagram

GitHub URL

Workflow Repository