π Deterministic UI Testing via API Virtualization
Modern frontend Single Page Applications (SPAs) depend heavily on asynchronous REST and GraphQL endpoints for data rendering, authorization gates, and operational telemetry. End-to-end testing against live staging environments often introduces test flakiness due to schema drift, rate-limiting, third-party vendor outages, or slow database migrations. Playwright Request Mocking allows engineering teams to construct virtual service layers directly within the browser runtime. Using page.route() and route.fulfill(), tests can decouple the user interface from backend infrastructure, inject static JSON fixtures, simulate high-latency edge networks, and validate critical UI recovery states under catastrophic 5xx failures.
LIVE ENDPOINT FLOW (High Latency, Environment-Dependent, Prone to Flakiness):
[ UI Component: fetch() ] ββNetwork SocketβββΊ [ Gateway / CDN ] βββΊ [ Staging DB ] βββΊ [ Response ]
VIRTUALIZED ROUTE MOCKING (Sub-millisecond, Deterministic, Offline-Capable):
[ UI Component: fetch() ]
β
βΌ (DevTools Protocol Hook)
[ Playwright Route Interceptor: page.route("**/api/v2/orders/*") ]
β
βββ Matches URL Pattern?
βββ YES βββΊ route.fulfill(status=200, json={...mockData...}) βββΊ Instantly renders UI!
βββ NO βββΊ route.continue_() βββΊ Hits external server
route.fulfill() accepts a native Python dictionary or list directly into the json keyword argument, automatically serializing the data and setting Content-Type: application/json.
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
# Define mock dataset using native Python structures
mock_inventory = [
{"sku": "SKU-901", "name": "Optic Sensor Relay", "price": "βΉ 1,299", "in_stock": True},
{"sku": "SKU-902", "name": "Industrial IoT Gateway", "price": "βΉ 4,850", "in_stock": True}
]
# Intercept API endpoint and supply JSON directly
page.route("**/api/v1/catalog/items", lambda route: route.fulfill(
status=200,
json=mock_inventory
))
page.set_content("""
Warehouse Inventory Hub
Loading items...
""")
first_item = page.locator("#items-list li").first
expect(first_item).to_have_text("Optic Sensor Relay - βΉ 1,299")
items_count = page.locator("#items-list li").count()
print(f"Mocked items rendered in DOM: {items_count}")
print(f"Verified First Item Text : '{first_item.inner_text()}'")
browser.close()
path.
import os
import json
import tempfile
from playwright.sync_api import sync_playwright, expect
# Setup external temporary fixture file simulating tests/fixtures/user_account.json
temp_dir = tempfile.gettempdir()
fixture_file = os.path.join(temp_dir, "account_fixture.json")
with open(fixture_file, "w") as f:
json.dump({
"account_id": "ACC-IN-2026",
"company": "Nikita Infotech Systems",
"tier": "Enterprise Premier",
"active_seats": 48
}, f)
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
# Route fulfill points directly to the external JSON fixture path
page.route("**/api/account/details", lambda route: route.fulfill(
status=200,
content_type="application/json",
path=fixture_file
))
page.set_content("""
Account Summary
Pending...
Pending...
""")
company_label = page.locator("#company-name")
plan_label = page.locator("#plan-tier")
expect(company_label).to_have_text("Nikita Infotech Systems")
expect(plan_label).to_have_text("Enterprise Premier")
print(f"Loaded external fixture successfully: '{company_label.inner_text()}' ({plan_label.inner_text()})")
browser.close()
if os.path.exists(fixture_file):
os.remove(fixture_file)
import time
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
def delayed_fulfillment(route):
# Simulate network latency (e.g. 500ms delay)
time.sleep(0.5)
route.fulfill(
status=200,
json={"status": "READY", "summary": "Financial Records Reconciled"}
)
page.route("**/api/reconcile", delayed_fulfillment)
page.set_content("""
Idle
""")
btn = page.locator("#reconcile-btn")
spinner = page.locator("#spinner")
result = page.locator("#result")
# Click to start delayed request
btn.click()
# Verify intermediate loading state is visible
expect(spinner).to_be_visible()
print("Intermediate loading spinner observed during network delay.")
# Auto-waiting assertion verifies final state once route completes
expect(spinner).to_be_hidden()
expect(result).to_have_text("Financial Records Reconciled")
print(f"Final state settled: '{result.inner_text()}'")
browser.close()
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
# Intercept session validation endpoint and return HTTP 401 Unauthorized
page.route("**/api/v1/session/verify", lambda route: route.fulfill(
status=401,
json={"error": "SESSION_EXPIRED", "message": "Access token has expired."}
))
page.set_content("""
""")
page.locator("#check-auth").click()
modal = page.locator("#auth-modal")
expect(modal).to_be_visible()
expect(modal.locator("h3")).to_have_text("Session Expired")
print(f"Frontend correctly handled HTTP 401: Modal displayed '{modal.locator('h3').inner_text()}'")
browser.close()
/graphql URL via HTTP POST. Inspect the request's post data to conditionally fulfill specific GraphQL operations while letting others pass through.
import json
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
def handle_graphql(route):
post_data = route.request.post_data_json or {}
operation_name = post_data.get("operationName")
if operation_name == "GetUserProfile":
route.fulfill(
status=200,
json={
"data": {
"user": {"id": "U-100", "username": "pooja_patil", "role": "Lead Architect"}
}
}
)
elif operation_name == "GetOrderHistory":
route.fulfill(
status=200,
json={
"data": {
"orders": [{"id": "ORD-1", "total": "βΉ 4,500"}]
}
}
)
else:
route.continue_()
page.route("**/graphql", handle_graphql)
page.set_content("""
GraphQL Dashboard
Querying user...
""")
user_label = page.locator("#user-display")
expect(user_label).to_have_text("pooja_patil (Lead Architect)")
print(f"GraphQL operation 'GetUserProfile' mocked successfully: '{user_label.inner_text()}'")
browser.close()
page.route() to match complex dynamic query strings, search parameters, and paginated URLs.
import re
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
# Matches: /api/v2/search?query=...&page=...
search_pattern = re.compile(r".*/api/v2/search\?query=.*&page=\d+")
def handle_search(route):
url = route.request.url
print(f"Intercepted Regex Matched URL: {url}")
route.fulfill(
status=200,
json={
"query": "playwright",
"total_results": 1,
"items": [{"title": "Mastering Playwright Python", "link": "/course/pw-py"}]
}
)
page.route(search_pattern, handle_search)
page.set_content("""
Search Engine
Searching...
""")
results_div = page.locator("#results")
expect(results_div).to_have_text("Found 1: Mastering Playwright Python")
print(f"Search results successfully verified: '{results_div.inner_text()}'")
browser.close()
BrowserContext to ensure multi-tab workflows, popups, and iframes share the same virtual service layer without registering routes on each tab individually.
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
# Define route rule on the BrowserContext level
context = browser.new_context()
context.route("**/api/config/flags", lambda route: route.fulfill(
status=200,
json={"feature_beta_export": True, "maintenance_mode": False}
))
# Tab 1: Opens and fetches configuration
tab1 = context.new_page()
tab1.set_content("""
Loading...
""")
# Tab 2: Opens in parallel and accesses the same endpoint
tab2 = context.new_page()
tab2.set_content("""
Loading...
""")
expect(tab1.locator("#t1-flag")).to_have_text("ENABLED")
expect(tab2.locator("#t2-flag")).to_have_text("ENABLED")
print(f"Context-level route applied to Tab 1: '{tab1.locator('#t1-flag').inner_text()}'")
print(f"Context-level route applied to Tab 2: '{tab2.locator('#t2-flag').inner_text()}'")
context.close()
browser.close()
page.unroute() to transition from mock data back to live backend integration dynamically.
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
handler_calls = 0
def mock_handler(route):
nonlocal handler_calls
handler_calls += 1
route.fulfill(status=200, body="MOCKED_RESPONSE")
target_pattern = "**/api/ping"
# Step 1: Register mock route
page.route(target_pattern, mock_handler)
# Trigger request 1
page.goto("https://example.com")
res1 = page.evaluate("() => fetch('/api/ping').then(r => r.text())")
print(f"Request 1 Result (Route Active) : '{res1}'")
# Step 2: Unroute pattern
page.unroute(target_pattern, mock_handler)
print("Deregistered route handler with page.unroute()")
print(f"Total times mock handler was executed: {handler_calls}")
browser.close()
PLAYWRIGHT ROUTE MOCKING & VIRTUALIZATION MATRIX:
ββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Method / Argument β Types β Description / Primary Use Case β
ββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β page.route() / context.route β url: str / Pattern, handler β Intercepts matching requests at page or context scope. β
β route.fulfill(status=...) β status: int (default: 200) β Returns custom HTTP status code (200, 401, 500, etc.). β
β route.fulfill(json=...) β json: Dict / List β Directly passes Python dictionary/list as JSON payload. β
β route.fulfill(body=...) β body: str / bytes β Supplies raw string or binary response body. β
β route.fulfill(path=...) β path: str β Hydrates response body directly from external file. β
β route.fulfill(headers=...) β headers: Dict[str, str] β Sets custom HTTP response headers. β
β route.fulfill(content_type=) β content_type: str β Shortcut for setting Content-Type header. β
β route.abort(error_code=...) β error_code: Optional[str] β Fails request with connection error ("failed", etc.). β
β route.continue_() β headers, post_data, method β Forwards request to real server with optional overrides.β
β route.fetch() β kwargs β Fetches real upstream response for inspect-and-modify. β
β page.unroute() β url, handler β Deregisters active route pattern. β
ββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ