Mobile Emulation and Responsive Testing
Test responsive layouts with Selenium: Chrome mobile emulation, breakpoint sizes, touch gestures, BiDi viewports, and when to use real devices via Appium.
More than half of web traffic comes from phones, yet most Selenium suites run at a single desktop resolution. Layout bugs at small widths (a hamburger menu that never opens, a sticky footer covering the submit button, a table that overflows) are among the most common production defects, and they are cheap to catch.
There are three levels of fidelity, each with a different cost:
| Approach | What it simulates | What it misses | Cost |
|---|---|---|---|
| Resize the window | Viewport width, CSS media queries | Device pixel ratio, touch, mobile user agent, mobile browser quirks | Free; any browser |
Browser device emulation (Chrome mobileEmulation, BiDi emulation) | Viewport, pixel ratio, user agent, touch events, pointer: coarse | Real mobile rendering engine, OS keyboard, performance, Safari on iOS | Free; Chromium (BiDi broadening) |
| Real devices or simulators via Appium | Everything: real Mobile Safari, Chrome for Android, native keyboards, hardware | Nothing, but slow and expensive | Device lab or cloud subscription |
Most teams should do the first two in every pipeline and the third for a small set of critical journeys.
Responsive Breakpoints with Window Sizes
If your concern is CSS layout at different widths, resizing the window is enough, and it works in every browser.
record Breakpoint(String name, int width, int height) {}
static final List<Breakpoint> BREAKPOINTS = List.of( new Breakpoint("mobile", 390, 844), new Breakpoint("tablet", 820, 1180), new Breakpoint("desktop", 1440, 900));
@ParameterizedTest@MethodSource("breakpoints")void navigationIsReachable(Breakpoint bp) { driver.manage().window().setSize(new Dimension(bp.width(), bp.height())); driver.get("https://app.example.com");
if (bp.width() < 768) { driver.findElement(By.cssSelector("[aria-label='Open menu']")).click(); } WebElement link = new WebDriverWait(driver, Duration.ofSeconds(5)) .until(ExpectedConditions.elementToBeClickable(By.linkText("Pricing"))); link.click(); assertTrue(driver.getCurrentUrl().endsWith("/pricing"));}import pytest
BREAKPOINTS = [("mobile", 390, 844), ("tablet", 820, 1180), ("desktop", 1440, 900)]
@pytest.mark.parametrize("name,width,height", BREAKPOINTS)def test_navigation_is_reachable(driver, name, width, height): driver.set_window_size(width, height) driver.get("https://app.example.com")
if width < 768: driver.find_element(By.CSS_SELECTOR, "[aria-label='Open menu']").click() WebDriverWait(driver, 5).until( EC.element_to_be_clickable((By.LINK_TEXT, "Pricing"))).click() assert driver.current_url.endswith("/pricing")const BREAKPOINTS = [{ name: 'mobile', width: 390, height: 844 },{ name: 'tablet', width: 820, height: 1180 },{ name: 'desktop', width: 1440, height: 900 },];
for (const bp of BREAKPOINTS) {it(`navigation is reachable on ${bp.name}`, async () => { await driver.manage().window().setRect({ width: bp.width, height: bp.height }); await driver.get('https://app.example.com');
if (bp.width < 768) { await driver.findElement(By.css("[aria-label='Open menu']")).click(); } const link = await driver.wait(until.elementLocated(By.linkText('Pricing')), 5000); await driver.wait(until.elementIsVisible(link), 5000); await link.click(); assert.ok((await driver.getCurrentUrl()).endsWith('/pricing'));});}private static readonly object[] Breakpoints ={ new object[] { "mobile", 390, 844 }, new object[] { "tablet", 820, 1180 }, new object[] { "desktop", 1440, 900 },};
[TestCaseSource(nameof(Breakpoints))]public void NavigationIsReachable(string name, int width, int height){ driver.Manage().Window.Size = new Size(width, height); driver.Navigate().GoToUrl("https://app.example.com");
if (width < 768) driver.FindElement(By.CssSelector("[aria-label='Open menu']")).Click();
var link = new WebDriverWait(driver, TimeSpan.FromSeconds(5)) .Until(d => d.FindElements(By.LinkText("Pricing")).FirstOrDefault(e => e.Displayed && e.Enabled)); link.Click(); Assert.That(driver.Url, Does.EndWith("/pricing"));}Window size is not viewport size
setSize sets the outer window, including browser chrome (tabs, toolbars, borders). On a headed Chrome the viewport might be 85 pixels shorter and, on some platforms, 16 pixels narrower than the number you set. That matters when you test exactly at a breakpoint: 768 outer may be 752 inner, which is the mobile layout.
Two reliable ways around it:
- Run headless, where window size and viewport size match (no chrome), with
--window-size=390,844. - Measure and correct: read
window.innerWidth, compute the difference, and resize again.
Also be careful at small widths: desktop Chrome enforces a minimum window width (around 500 pixels on some platforms when headed). Headless mode or device emulation avoids that limit.
Tip: Pick breakpoint test widths a few pixels inside each range (for example 390, 820, 1440) rather than exactly on the breakpoint. Exact-boundary tests are where off-by-one CSS and the window/viewport discrepancy bite.
Chrome Mobile Emulation
Chrome’s DevTools device mode is available to Selenium through the mobileEmulation option. Beyond viewport size it sets the device pixel ratio, the user agent string, touch event support and the (pointer: coarse) and (hover: none) media features. That makes the server send the mobile site if it sniffs user agents, and makes touch-only JavaScript paths run.
ChromeOptions options = new ChromeOptions();
// Named device from Chrome DevTools' list (names change between Chrome versions)options.setExperimentalOption("mobileEmulation", Map.of("deviceName", "Pixel 7"));
// Or explicit metrics: more stable across Chrome versionsMap<String, Object> metrics = Map.of("width", 390, "height", 844, "pixelRatio", 3.0, "touch", true);options.setExperimentalOption("mobileEmulation", Map.of( "deviceMetrics", metrics, "userAgent", "Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/142.0.0.0 Mobile Safari/537.36"));
WebDriver driver = new ChromeDriver(options);options = webdriver.ChromeOptions()
# Named deviceoptions.add_experimental_option("mobileEmulation", {"deviceName": "Pixel 7"})
# Or explicit metricsoptions.add_experimental_option("mobileEmulation", { "deviceMetrics": {"width": 390, "height": 844, "pixelRatio": 3.0, "touch": True}, "userAgent": ("Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 " "(KHTML, like Gecko) Chrome/142.0.0.0 Mobile Safari/537.36"),})
driver = webdriver.Chrome(options=options)const chrome = require('selenium-webdriver/chrome');
// Named devicelet options = new chrome.Options().setMobileEmulation({ deviceName: 'Pixel 7' });
// Or explicit metricsoptions = new chrome.Options().setMobileEmulation({deviceMetrics: { width: 390, height: 844, pixelRatio: 3.0, touch: true },userAgent: 'Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 ' + '(KHTML, like Gecko) Chrome/142.0.0.0 Mobile Safari/537.36',});
const driver = await new Builder().forBrowser('chrome').setChromeOptions(options).build();var options = new ChromeOptions();
// Named deviceoptions.EnableMobileEmulation("Pixel 7");
// Or explicit metricsoptions.EnableMobileEmulation(new ChromiumMobileEmulationDeviceSettings{ Width = 390, Height = 844, PixelRatio = 3.0, EnableTouchEvents = true, UserAgent = "Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/142.0.0.0 Mobile Safari/537.36",});
var driver = new ChromeDriver(options);Prefer explicit deviceMetrics over deviceName in a long-lived suite. The device list comes from Chrome itself, devices are added and removed, and an unknown name fails session creation with a SessionNotCreatedException (see Session Not Created). Explicit metrics also make it obvious in the code what is being tested.
Newer ChromeDriver versions also accept a clientHints object in mobileEmulation (platform, mobile flag, brands) for sites that use User-Agent Client Hints instead of the UA string. Use it if your server-side device detection relies on Sec-CH-UA-Mobile.
What emulation does not give you: Mobile Safari’s rendering and its many quirks (viewport height with the collapsing address bar, position: fixed behaviour, date inputs), Android Chrome’s actual GPU and CPU constraints, the on-screen keyboard resizing the viewport, or OS permission dialogs. Emulation is a layout and behaviour check in desktop Chrome, not a device test.
Viewport Emulation with BiDi
WebDriver BiDi standardises device emulation across browsers. browsingContext.setViewport sets the CSS viewport and device pixel ratio for a tab, independent of the window size, in Chrome, Edge and Firefox. It is the cleanest way to get an exact viewport.
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
// options.setCapability("webSocketUrl", true)BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());context.setViewport(390, 844, 3.0);
driver.get("https://app.example.com");Long innerWidth = (Long) ((JavascriptExecutor) driver).executeScript("return window.innerWidth;");assertEquals(390L, innerWidth);# options.enable_bidi = Truedriver.browsing_context.set_viewport( context=driver.current_window_handle, viewport={"width": 390, "height": 844}, device_pixel_ratio=3,)
driver.get("https://app.example.com")assert driver.execute_script("return window.innerWidth;") == 390const BrowsingContext = require('selenium-webdriver/bidi/browsingContext');
// options.enableBidi()const context = await BrowsingContext(driver, { browsingContextId: await driver.getWindowHandle() });await context.setViewport(390, 844, 3);
await driver.get('https://app.example.com');assert.strictEqual(await driver.executeScript('return window.innerWidth;'), 390);The C# BiDi API also exposes viewport emulation on the browsing context, but its method and option names have changed between recent releases; check the current API docs for your version rather than copying an example. The BiDi emulation module adds screen orientation, touch, user agent, geolocation and more, covered in WebDriver BiDi and, for location and locale, in Geolocation, Timezone and Locale.
Note: A viewport set through BiDi applies to that browsing context only. A link that opens a new tab gets the default viewport again; set it on the new context too.
Touch Actions
Under mobile emulation, many components listen for touchstart/touchend or pointer events with pointerType === 'touch'. A mouse click still works for simple taps, but swipes, long-presses and pinch gestures need touch input. The W3C Actions API supports a touch pointer type.
import org.openqa.selenium.interactions.PointerInput;import org.openqa.selenium.interactions.Sequence;
WebElement carousel = driver.findElement(By.cssSelector("[data-testid='carousel']"));Rectangle r = carousel.getRect();int y = r.getY() + r.getHeight() / 2;int startX = r.getX() + (int) (r.getWidth() * 0.8);int endX = r.getX() + (int) (r.getWidth() * 0.2);
PointerInput finger = new PointerInput(PointerInput.Kind.TOUCH, "finger");Sequence swipe = new Sequence(finger, 0) .addAction(finger.createPointerMove(Duration.ZERO, PointerInput.Origin.viewport(), startX, y)) .addAction(finger.createPointerDown(PointerInput.MouseButton.LEFT.asArg())) .addAction(finger.createPointerMove(Duration.ofMillis(250), PointerInput.Origin.viewport(), endX, y)) .addAction(finger.createPointerUp(PointerInput.MouseButton.LEFT.asArg()));
((RemoteWebDriver) driver).perform(List.of(swipe));from selenium.webdriver.common.actions import interactionfrom selenium.webdriver.common.actions.action_builder import ActionBuilderfrom selenium.webdriver.common.actions.pointer_input import PointerInput
carousel = driver.find_element(By.CSS_SELECTOR, "[data-testid='carousel']")r = carousel.recty = int(r["y"] + r["height"] / 2)start_x = int(r["x"] + r["width"] * 0.8)end_x = int(r["x"] + r["width"] * 0.2)
finger = PointerInput(interaction.POINTER_TOUCH, "finger")actions = ActionBuilder(driver, mouse=finger, duration=250)actions.pointer_action.move_to_location(start_x, y).pointer_down() \ .move_to_location(end_x, y).pointer_up()actions.perform()using OpenQA.Selenium.Interactions;
var carousel = driver.FindElement(By.CssSelector("[data-testid='carousel']"));var loc = carousel.Location;var size = carousel.Size;int y = loc.Y + size.Height / 2;int startX = loc.X + (int)(size.Width * 0.8);int endX = loc.X + (int)(size.Width * 0.2);
var finger = new PointerInputDevice(PointerKind.Touch, "finger");var swipe = new ActionBuilder() .AddAction(finger.CreatePointerMove(CoordinateOrigin.Viewport, startX, y, TimeSpan.Zero)) .AddAction(finger.CreatePointerDown(MouseButton.Touch)) .AddAction(finger.CreatePointerMove(CoordinateOrigin.Viewport, endX, y, TimeSpan.FromMilliseconds(250))) .AddAction(finger.CreatePointerUp(MouseButton.Touch));
((IActionExecutor)driver).PerformActions(swipe.ToActionSequenceList());The JavaScript Actions builder in selenium-webdriver is built around the default mouse and keyboard devices and does not offer a documented way to add a touch pointer, so JavaScript suites usually dispatch swipes with a mouse drag (which pointer-event based libraries accept) or move gesture tests to Appium. The general Actions API is covered in Mouse Actions.
Touch input in desktop Chrome is only meaningful when touch emulation is on ("touch": true in deviceMetrics, or a named device). Without it the page sees a desktop browser with no touch support and may ignore touch events entirely.
When You Need Real Devices: Appium
Emulation answers “does the responsive layout work”. It cannot answer “does checkout work in Mobile Safari on an iPhone” or “does our hybrid app’s native login screen work”. For that you need a real browser engine on a real (or simulated) device, and in the WebDriver world that means Appium.
Appium is a WebDriver server for mobile and desktop platforms. Your test code uses the same W3C protocol and largely the same API you already know: the Appium client libraries (io.appium:java-client, Appium-Python-Client, webdriverio, Appium.WebDriver for .NET) extend the Selenium bindings.
Since Appium 2 the server is a small core plus separately installed drivers (and plugins), a model Appium 3 keeps:
npm i -g appiumappium driver install uiautomator2 # Android (native, hybrid, Chrome)appium driver install xcuitest # iOS and iPadOS (native, hybrid, Safari)appium driver install windows # Windows desktop appsappium driver install mac2 # macOS desktop appsappium # start the server on :4723// io.appium:java-clientimport io.appium.java_client.ios.IOSDriver;import io.appium.java_client.ios.options.XCUITestOptions;
XCUITestOptions options = new XCUITestOptions() .setPlatformVersion("18.0") .setDeviceName("iPhone 16");options.setCapability("browserName", "Safari");
IOSDriver driver = new IOSDriver(new URL("http://127.0.0.1:4723"), options);driver.get("https://app.example.com/checkout");driver.findElement(By.cssSelector("[data-testid='pay']")).click();# pip install Appium-Python-Clientfrom appium import webdriverfrom appium.options.ios import XCUITestOptions
options = XCUITestOptions()options.platform_version = "18.0"options.device_name = "iPhone 16"options.set_capability("browserName", "Safari")
driver = webdriver.Remote("http://127.0.0.1:4723", options=options)driver.get("https://app.example.com/checkout")# From here, regular Selenium-style element interaction against real Mobile Safaridriver.find_element("css selector", "[data-testid='pay']").click()Practical guidance for real-device testing:
- Use a device cloud (BrowserStack, Sauce Labs, LambdaTest and others) unless you have a strong reason to maintain a device lab. See Cloud Testing Platforms.
- Keep the real-device suite small: login, search, checkout, the flows that make money. Run the broad responsive suite under emulation.
- Share page objects where you can. Mobile web on a real device uses the same DOM and the same locators; only driver creation differs. Isolate that in your driver factory.
- Expect slower, flakier runs. Device boot, network over USB or to a cloud, and OS dialogs all add latency. Generous explicit waits and retries at the infrastructure level are normal here.
A Sensible Mobile Strategy
- Every pull request: functional smoke tests at two or three breakpoint widths, headless, any browser.
- Every pull request touching front-end code: Chrome mobile emulation for touch-specific components, plus visual regression snapshots at mobile and desktop widths.
- Nightly or pre-release: critical journeys on real iOS Safari and Android Chrome via Appium on a device cloud.
- Production: real-user monitoring segmented by device class to find the problems none of the above predicted.
Summary
- Window resizing covers CSS breakpoints in every browser; run headless or measure
innerWidthso window and viewport sizes match. - Chrome
mobileEmulationadds pixel ratio, mobile user agent and touch; prefer explicitdeviceMetricsover named devices. - BiDi
setViewportgives an exact viewport cross-browser; the wider BiDi emulation module is still settling. - Use a touch
PointerInputfor swipes and long-presses under emulation. - Real Safari, real Android and native apps need Appium (drivers installed separately since Appium 2), ideally on a device cloud, for a small set of critical flows.
Finished this lesson?
Mark it complete to track your progress through the course. Saved in this browser only.