📱 Responsive Testing & Device Emulation Architecture
Modern web applications must perform consistently across diverse hardware: desktop monitors, foldable tablets, and mobile smartphones. Playwright enables end-to-end device emulation through native browser capabilities rather than simple iframe resizing. By configuring viewports, user agents, device scale factors (Retina displays), touch screen interfaces, and screen orientations, test suites can validate responsive navigation bars, hamburger menus, and touch events without requiring expensive physical device farms.
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
# Query exact parameters of pre-configured device profiles
pixel_7 = p.devices["Pixel 7"]
iphone_14 = p.devices["iPhone 14 Pro"]
print("=== Pixel 7 Emulation Profile ===")
print(f" User Agent : {pixel_7['user_agent'][:50]}...")
print(f" Viewport Geometry: {pixel_7['viewport']['width']}x{pixel_7['viewport']['height']}")
print(f" Scale Factor : {pixel_7['device_scale_factor']}x")
print(f" Touch Enabled : {pixel_7['has_touch']}")
print(f" Mobile Mode : {pixel_7['is_mobile']}")
print("\n=== iPhone 14 Pro Emulation Profile ===")
print(f" Viewport Geometry: {iphone_14['viewport']['width']}x{iphone_14['viewport']['height']}")
print(f" Scale Factor : {iphone_14['device_scale_factor']}x")
browser.new_context(**profile) to launch an authentic mobile browser session and test responsive viewports.
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
# Load mobile profile and spawn context
mobile_profile = p.devices["Pixel 7"]
context = browser.new_context(**mobile_profile)
page = context.new_page()
page.goto("https://demo.playwright.dev/todomvc/")
# Evaluate client-side properties inside the browser runtime
device_metrics = page.evaluate("""() => ({
innerWidth: window.innerWidth,
innerHeight: window.innerHeight,
pixelRatio: window.devicePixelRatio,
isTouch: 'ontouchstart' in window,
userAgent: navigator.userAgent
})""")
print("Client DOM Evaluation Results:")
print(f" Rendered Viewport : {device_metrics['innerWidth']}x{device_metrics['innerHeight']} px")
print(f" Device Pixel Ratio: {device_metrics['pixelRatio']}")
print(f" Touch Event API : {'Supported' if device_metrics['isTouch'] else 'Disabled'}")
context.close()
browser.close()
page.set_viewport_size() without having to restart the browser context.
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.goto("https://example.com")
# Responsive testing breakpoints
test_breakpoints = [
("Desktop 1080p", 1920, 1080),
("Laptop Widescreen", 1366, 768),
("Tablet Portrait", 768, 1024),
("Mobile View", 375, 667)
]
for label, width, height in test_breakpoints:
page.set_viewport_size({"width": width, "height": height})
actual_size = page.viewport_size
print(f"Breakpoint [{label:18s}] -> Applied: {actual_size['width']}x{actual_size['height']} px")
browser.close()
has_touch=True is configured, Playwright dispatches real TouchEvents (touchstart, touchmove, touchend) and supports mobile screen tap interactions via page.tap().
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
# Configure custom context with touch dispatch enabled
context = browser.new_context(
viewport={"width": 390, "height": 844},
has_touch=True,
is_mobile=True
)
page = context.new_page()
# Load interactive demo application
page.goto("https://demo.playwright.dev/todomvc/")
todo_input = page.get_by_placeholder("What needs to be done?")
todo_input.fill("Touch Gesture Verification")
todo_input.press("Enter")
# Tap on the toggle button using touch interface
toggle_checkbox = page.locator(".toggle")
toggle_checkbox.tap()
is_completed = page.locator(".todo-list li").first.get_attribute("class")
print("Mobile Tap Event Dispatched Successfully.")
print(f"Todo Item State: '{is_completed}'")
context.close()
browser.close()
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
# Base iPad device profile
ipad_profile = p.devices["iPad Pro 11"]
context = browser.new_context(**ipad_profile)
page = context.new_page()
page.goto("https://example.com")
# 1. Default Portrait Mode
portrait_size = page.viewport_size
print(f"iPad Portrait Viewport : {portrait_size['width']}x{portrait_size['height']} px")
# 2. Simulate Device Rotation to Landscape Mode (Swap Width and Height)
landscape_size = {"width": portrait_size["height"], "height": portrait_size["width"]}
page.set_viewport_size(landscape_size)
print(f"iPad Landscape Viewport: {page.viewport_size['width']}x{page.viewport_size['height']} px")
# Assert layout accommodates wider landscape layout
rendered_width = page.evaluate("window.innerWidth")
print(f"Verified Active Window Width: {rendered_width} px")
context.close()
browser.close()
device_scale_factor captures high-resolution screenshots and tests responsive srcset images.
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
# 1. Standard Desktop 1x Density Context
std_context = browser.new_context(viewport={"width": 800, "height": 600}, device_scale_factor=1)
std_page = std_context.new_page()
std_page.goto("https://example.com")
std_dpr = std_page.evaluate("window.devicePixelRatio")
# 2. Apple Retina 2x Density Context
retina_context = browser.new_context(viewport={"width": 800, "height": 600}, device_scale_factor=2)
retina_page = retina_context.new_page()
retina_page.goto("https://example.com")
retina_dpr = retina_page.evaluate("window.devicePixelRatio")
print(f"Standard Display window.devicePixelRatio: {std_dpr}")
print(f"Retina 2x Display window.devicePixelRatio: {retina_dpr}")
print("Retina screenshots will render at double pixel resolution (1600x1200 image buffer).")
std_context.close()
retina_context.close()
browser.close()
page.emulate_media() to test print preview stylesheets (@media print) and color schemes (prefers-color-scheme: dark).
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.goto("https://example.com")
# 1. Emulate Print Media Stylesheet
page.emulate_media(media="print")
is_print = page.evaluate("window.matchMedia('print').matches")
print(f"Print Media Active: {is_print}")
# 2. Emulate Dark Mode Color Scheme
page.emulate_media(color_scheme="dark")
is_dark = page.evaluate("window.matchMedia('(prefers-color-scheme: dark)').matches")
print(f"Dark Mode Scheme Active: {is_dark}")
# 3. Emulate Reduced Motion (Accessibility preference)
page.emulate_media(reduced_motion="reduce")
reduced_motion = page.evaluate("window.matchMedia('(prefers-reduced-motion: reduce)').matches")
print(f"Reduced Motion Preference Active: {reduced_motion}")
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()
# Load responsive HTML with media queries
page.set_content("""
""")
# 1. Test Desktop Breakpoint (1280px wide)
page.set_viewport_size({"width": 1280, "height": 720})
expect(page.locator("#desktop-nav")).to_be_visible()
expect(page.locator("#mobile-hamburger")).to_be_hidden()
print("Desktop Viewport (1280px): Navigation links visible, hamburger button hidden.")
# 2. Test Mobile Breakpoint (375px wide)
page.set_viewport_size({"width": 375, "height": 667})
expect(page.locator("#desktop-nav")).to_be_hidden()
expect(page.locator("#mobile-hamburger")).to_be_visible()
print("Mobile Viewport (375px) : Navigation links collapsed, hamburger button visible.")
browser.close()
import pytest
from playwright.sync_api import sync_playwright
DEVICE_MATRIX = ["Desktop Chrome", "iPhone 13", "iPad Pro 11", "Pixel 7"]
def execute_device_test(device_name: str):
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
if device_name == "Desktop Chrome":
context = browser.new_context(viewport={"width": 1280, "height": 800})
else:
context = browser.new_context(**p.devices[device_name])
page = context.new_page()
page.goto("https://demo.playwright.dev/todomvc/")
# Verify page renders and remains interactive across all devices
todo_box = page.get_by_placeholder("What needs to be done?")
todo_box.fill(f"Item on {device_name}")
todo_box.press("Enter")
count = page.locator(".todo-list li").count()
print(f"Device [{device_name:15s}] -> 1 Item created successfully.")
context.close()
browser.close()
# Simulate Pytest parameterized execution loop
for dev in DEVICE_MATRIX:
execute_device_test(dev)
browser.new_context() and page.set_viewport_size().
DEVICE EMULATION PROPERTIES MATRIX:
┌──────────────────────────────┬────────────────────────┬──────────────────────┬─────────────────────────────────────────────────────────┐
│ Property │ Type │ Default │ Description / Use Case │
├──────────────────────────────┼────────────────────────┼──────────────────────┼─────────────────────────────────────────────────────────┤
│ viewport │ Dict[str, int] │ {"width": 1280, ...} │ Sets the browser viewport dimensions (width, height). │
│ is_mobile │ bool │ False │ Emulates meta viewport tags and mobile browser behavior.│
│ has_touch │ bool │ False │ Enables TouchEvent API and touch gesture interactions. │
│ device_scale_factor │ float / int │ 1 │ Pixel density multiplier (e.g., 2 or 3 for Retina/OLED).│
│ user_agent │ str │ Default Engine UA │ Emulates mobile/tablet User-Agent headers. │
│ color_scheme │ str │ "no-preference" │ Toggles CSS color modes: "light", "dark", "no-pref...". │
│ reduced_motion │ str │ "no-preference" │ Toggles accessibility preference: "reduce" or "no-pref".│
│ forced_colors │ str │ "none" │ Toggles high-contrast accessibility mode: "active". │
│ page.set_viewport_size() │ Dict[str, int] │ Dynamic │ Updates active viewport size on an existing page. │
│ page.emulate_media() │ kwargs │ Dynamic │ Overrides media query types ("print", "screen"). │
└──────────────────────────────┴────────────────────────┴──────────────────────┴─────────────────────────────────────────────────────────┘