Cross-Browser and Cross-Platform Testing Questions
Verifying that a product behaves consistently across browsers, browser versions, operating systems, devices, and screen sizes. Covers building a browser and device coverage matrix, prioritizing platforms by real usage telemetry, deciding what to automate versus leave to manual exploratory checks, risk-based sampling between PR, nightly, and pre-release runs with escalation to the full matrix, wiring cross-browser suites into CI with parallel and selective runs, cloud grids versus self-hosted labs (Selenium Grid in Docker, on-prem device labs) versus emulators and simulators, real devices and native mobile apps, sizing infrastructure for large numbers of parallel sessions, running one suite across Chromium, Firefox, and WebKit (Playwright projects, driver factories driven by environment config), headless versus headed differences, feature detection versus user-agent sniffing, browser-specific defects (Safari timing and event ordering, cookie policy and third-party embeds, font and DPI rendering, input and event differences) and how to debug them on physical devices, and OS-level differences (filesystem, encoding, endianness, numeric behavior). Excludes framework and Page Object design, flaky-test management, locator and wait mechanics, and accessibility or visual-diff tooling, which are covered elsewhere.
Describe how to integrate a cross-browser test suite into a CI/CD pipeline for PR gating that supports parallel execution and selective test runs based on changed code paths. Include a high-level example workflow in a common CI system such as GitHub Actions, and explain how you would shard tests across runners to minimise PR latency.
Sample Answer
Direct answer
Gate pull requests (PRs) with one required check (a check that branch protection, the repository setting that blocks merging until named checks pass, must see succeed) backed by a pipeline of four stages: a cheap "select" job that maps the changed files to test tags, a matrix of parallel jobs that each run one shard (a fixed slice) of the Playwright suite in a pinned browser image, a merge job that combines the per-shard reports (each shard writes a blob report, a compact raw results file that can be merged into one HTML report later), and a single gate job that is the only check branch protection names. Run engine-sensitive tests on Chromium, Firefox and WebKit and everything else on Chromium only; choose the shard count from the latency budget with the arithmetic below, not by guessing.
Selective runs from changed code paths
Playwright's --only-changed[=ref] flag runs test files that changed between HEAD and a git ref (git only, per the CLI docs). It selects changed test files, not tests affected by changed source files, so a change to src/checkout/ with no test edit would run nothing. Map source paths to tags instead, and pass the tags to --grep:
// select-tags.mjs
// Reads changed file paths (one per line) on stdin and prints one line for
// $GITHUB_OUTPUT: grep=<regex for npx playwright test --grep>.
import { readFileSync } from 'node:fs';
const rules = [
[/^src\/checkout\//, '@checkout'],
[/^src\/search\//, '@search'],
[/^src\/account\//, '@account'],
[/\.(md|png|svg)$|^docs\//, null], // no effect on behaviour
];
const runAll = /^(package(-lock)?\.json|playwright\.config\.ts|tests\/|src\/shared\/)/;
const files = readFileSync(0, 'utf8').split('\n').filter(Boolean);
const tags = new Set(['@smoke']);
let all = false;
let relevant = 0;
for (const f of files) {
if (runAll.test(f)) { all = true; continue; }
const rule = rules.find(([re]) => re.test(f));
if (rule && rule[1] === null) continue;
relevant++;
if (rule) tags.add(rule[1]); else all = true; // unknown path: be safe
}
console.log('grep=' + (all ? '.' : relevant === 0 ? 'NONE' : [...tags].join('|')));
Run in the Playwright 1.48.2 image it prints grep=@smoke|@checkout for src/checkout/cart.ts plus README.md, grep=. (run everything) for src/shared/format.ts, grep=NONE for only docs/a.md and logo.png, and grep=. for the unmapped src/legacy/x.ts. The safe default is "run everything" for shared code, test code, config, lockfiles and unknown paths: a wrong skip lets a bug through, a wrong full run only costs minutes.
A Playwright project is a named browser configuration in playwright.config.ts, and it can carry its own grep filter (for example Firefox and WebKit run only @engine tests). A command-line --grep is applied on top of it: with the project filters from a three-project config, --project=firefox --grep "@logic" listed 0 tests while --project=chromium --grep "@logic" listed 1. So a Firefox or WebKit run of a changed area needs the test to carry both the area tag and @engine.
The GitHub Actions workflow
name: e2e-pr
on: pull_request
concurrency:
group: e2e-${{ github.ref }}
cancel-in-progress: true
jobs:
select:
runs-on: ubuntu-latest
outputs:
grep: ${{ steps.pick.outputs.grep }}
steps:
- uses: actions/checkout@v4
with: { fetch-depth: 0 }
- id: pick
shell: bash
run: git diff --name-only origin/${{ github.base_ref }}...HEAD | node ci/select-tags.mjs >> "$GITHUB_OUTPUT"
e2e:
needs: select
if: needs.select.outputs.grep != 'NONE'
runs-on: ubuntu-latest
container: mcr.microsoft.com/playwright:v1.48.2-jammy
strategy:
fail-fast: false
matrix:
shard: [1, 2, 3, 4, 5, 6, 7, 8]
steps:
- uses: actions/checkout@v4
- run: npm ci
- run: npx playwright test --shard=${{ matrix.shard }}/8 --grep "${{ needs.select.outputs.grep }}"
env: { CI: "true" }
- uses: actions/upload-artifact@v4
if: ${{ !cancelled() }}
with:
name: blob-report-${{ matrix.shard }}
path: blob-report
retention-days: 1
merge-reports:
needs: e2e
if: ${{ !cancelled() && needs.e2e.result != 'skipped' }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci
- uses: actions/download-artifact@v5
with: { path: all-blob-reports, pattern: blob-report-*, merge-multiple: true }
- run: npx playwright merge-reports --reporter html ./all-blob-reports
- uses: actions/upload-artifact@v4
with: { name: playwright-report, path: playwright-report, retention-days: 14 }
gate:
needs: [select, e2e]
if: always()
runs-on: ubuntu-latest
steps:
- run: |
test "${{ needs.select.result }}" = "success"
test "${{ needs.e2e.result }}" = "success" -o "${{ needs.e2e.result }}" = "skipped"
How to read the workflow. concurrency with cancel-in-progress: true means a newer push to the same branch cancels the older run. fetch-depth: 0 makes checkout fetch the full git history (the default is a single commit, which would leave nothing to diff against). git diff --name-only origin/BASE...HEAD with three dots compares HEAD with the point where the branch left the base branch, so it lists only the files this PR changed, not files that landed on the base branch since. Appending grep=... to $GITHUB_OUTPUT (a file the runner reads) turns that line into the step output steps.pick.outputs.grep, which the select job passes on as needs.select.outputs.grep. shell: bash matters: a step with no shell runs bash -e, which has no pipefail, so if git diff failed (for example the base ref could not be resolved) the pipe would still succeed, the selector would read an empty list and print NONE, e2e would be skipped and the gate would pass with no tests run; the explicit bash shell runs bash -eo pipefail, so the failed git diff fails the step, and with it select and the gate. needs: select makes e2e wait for it, and the if: skips e2e entirely when the selector printed NONE. fail-fast: false lets the other shards finish when one fails, so you see every failure at once. needs.e2e.result is one of success, failure, cancelled or skipped, and if: always() makes the gate job run even when e2e failed or was skipped, which a job otherwise would not. The gate's first shell line requires select to have succeeded, because a failed select makes e2e skip and a skip alone must never read as a pass. Its second line, test A = success -o A = skipped, exits 0 (job passes) only if the e2e result is one of those two; GitHub runs multi-line run blocks with bash -e, so either line failing fails the job.
How to read select-tags.mjs. readFileSync(0, 'utf8') reads standard input (file descriptor 0), which is the piped list of changed paths. runAll is a regular expression for paths whose change could affect any test (lockfile, config, the tests themselves, shared code), and any match sets all. rules.find(([re]) => re.test(f)) returns the first [regex, tag] pair whose regex matches the path f; a null tag means the path cannot change behaviour and is ignored, no pair at all means an unknown path, which also sets all. The final console.log prints . (a regex that matches every test title) for run-everything, NONE for nothing relevant, and otherwise the tags joined by | into a regex such as @smoke|@checkout.
The config sets reporter: process.env.CI ? 'blob' : 'list' and fullyParallel: true. The Playwright docs recommend blob reports for sharded CI and fullyParallel so that shards split by test and not by file; without it, shards split by file and uneven file sizes leave some shards with far more tests. The gate job gives branch protection a single stable name, and treats a skipped e2e (documentation-only change) as a pass only when select succeeded. The container: image pins the browser builds to the Playwright version, and concurrency cancels a superseded run when a new commit is pushed.
Choosing the shard count
A shard is one of N slices of the suite run by its own CI job, and a worker is a parallel test process inside that job. Per-shard latency is roughly total test work divided by (shards x workers per job), plus fixed per-job overhead. Illustrative assumptions (ESTIMATE, replace with your measured values): 200 tests of which 60 are engine-sensitive, so 140 + 60 x 3 = 320 test executions; 15 s average per execution (4,800 s of work); 2 workers per job; 90 s of checkout, install and browser start-up per job.
One row worked out, 7 shards: latency = 4,800 / (7 x 2) + 90 = 342.9 + 90 = 432.9 s, shown as 433; runner minutes = 7 x 432.9 / 60 = 50.5.
| Shards | Latency (s) | Runner minutes |
|---|---|---|
| 1 | 2,490 | 41.5 |
| 4 | 690 | 46.0 |
| 7 | 433 | 50.5 |
| 8 | 390 | 52.0 |
| 16 | 240 | 64.0 |
For a 7-minute (420 s) PR budget, 7 shards miss it (433 s) and 8 shards meet it (390 s), at about 25 percent more runner minutes than a single job (52.0 against 41.5). The overhead term is why returns diminish: going from 8 to 16 shards saves 150 s (390 to 240) and costs 12 more runner minutes (52.0 to 64.0). Re-fit the numbers from the merged report's per-test durations once it exists.
Trade-offs and pitfalls
- A flaky test blocks every PR. Set
retries: 1in CI so one transient failure does not fail a shard, and track tests that needed a retry. - Tag drift: a new directory with no rule falls through to "run everything", which is safe and visible in the select job log.
- Playwright WebKit on Linux is not iOS Safari; keep real-device runs nightly.
Running the code
npm i @playwright/test@1.48.2
printf 'src/checkout/cart.ts\nREADME.md\n' | node select-tags.mjs
CI=true npx playwright test --shard=1/8 --list
npx playwright test --project=firefox --grep "@logic" --list
With this minimal playwright.config.ts and a tests/a.spec.ts holding two tests named totals @logic and layout @engine:
import { defineConfig } from '@playwright/test';
export default defineConfig({
fullyParallel: true,
reporter: process.env.CI ? 'blob' : 'list',
retries: process.env.CI ? 1 : 0,
projects: [
{ name: 'chromium', use: { browserName: 'chromium' } },
{ name: 'firefox', use: { browserName: 'firefox' }, grep: /@engine/ },
{ name: 'webkit', use: { browserName: 'webkit' }, grep: /@engine/ },
],
});
the Firefox command prints Error: No tests found and exits 1, while the same command with --project=chromium lists totals @logic. Run inside mcr.microsoft.com/playwright:v1.48.2-jammy with --rm.
Your team has a limited CI budget for browser testing across many OS, browser and device combinations. Design what runs on every PR, what runs nightly, and what runs before release, what triggers escalation to the full matrix, and how you would show the strategy is working.
Sample Answer
Direct answer
Run tests in three tiers with escalating cost, and spend the budget where defects and users are. Every PR runs the full suite on one primary engine plus a small smoke subset on the other two engines. Nightly runs the full suite on every engine and the emulated mobile set; a PR runs the emulated mobile set only when it escalates (for example because it touches global CSS). Before release, the full matrix runs, including real devices and the heavy runs (real rendering, throttled network). Defined triggers escalate a PR to the nightly or full matrix early, and a handful of measured outcomes show whether the strategy works.
Tier design
Illustrative suite for the arithmetic: 600 tests, 60 of them tagged smoke (critical journeys and engine-sensitive checks), three desktop engines (Chromium, Firefox, WebKit, the engine behind Safari), plus emulated mobile (a desktop browser with a phone's viewport, touch and user-agent).
| Tier | Runs | Test executions | How the number comes out |
|---|---|---|---|
| Every PR | Full suite on Chromium; smoke on Firefox and WebKit; selected tests for changed code first | 720 | 600 + 2 x 60 = 720 |
| Nightly | Full suite on all three engines; emulated mobile on the 120 tests tagged responsive, run on 2 phone profiles (one Chromium-based, one WebKit-based) | 2,040 | 3 x 600 + 2 x 120 = 2,040 |
| Before release | Nightly set, plus smoke on 3 real devices in a cloud device farm (hosted real phones and browsers), plus heavy runs | 2,220 plus heavy | 2,040 + 3 x 60 = 2,220 |
A PR costs 720 / 1,800 = 40 percent of the 1,800 executions (3 x 600) of running all 600 tests on three engines. The execution counts are for budgeting; wall-clock time depends on parallelism (splitting the tests into shards that run on separate machines at the same time) and is the second constraint.
Cutting cost without cutting coverage
Items 3 and 4 cut cost or time without moving any test, so they lose no coverage. Items 1, 2, 5 and 6 move tests between tiers or engines and need the measures in the last section to confirm nothing was lost, and item 7 is the order to cut in when money runs short.
- Prioritise by historical failures. Rank tests by failures in the last 30 days (and by which browser they failed on). Those run first in PR and fail the run early; tests that never failed in 90 days and never touch engine-sensitive code run last in the PR, on Chromium only, and reach the other engines only in the nightly run. The full Chromium suite stays in every PR, which is what keeps the 720 figure above true.
- Select by change. Map changed files to the tests that import or exercise them and run those first. If the budget allows, also run them on Firefox and WebKit in the PR, which adds 2 executions per such test beyond the smoke subset (for example, 40 changed-file tests outside the smoke set add 2 x 40 = 80, so the PR costs 720 + 80 = 800, which is 800 / 1,800 = 44 percent); the rest run on Chromium only.
- Reuse and cache. Build the app once and share the artifact across all jobs. Cache the browser binaries between jobs, keyed on the Playwright version, so each job does not re-download them. Reuse a warm container image with browsers already installed (warm-up) instead of installing them in every job.
- Shard. Split a project's tests across parallel machines; the total CPU stays the same, so the PR wall-clock drops.
- Cloud farm versus emulation split. Emulation (a desktop engine with a phone viewport) is cheap and goes in the nightly tier for layout and touch logic, and in a PR that escalates because it touches responsive layout or global CSS. A cloud farm bills for real devices, so it only runs release-gate smoke and the checks that need hardware (touch feel, on-screen keyboard behaviour, real performance).
- Sample the heavy runs progressively. Full-rendering runs (screenshots at several viewports) and network-throttled runs (a throttling preset such as the 3G preset in Chrome DevTools, which slows the network to mobile-like speeds) are the most expensive per test. Run them as a rotating slice: a seventh of the heavy set each night, all of it before release, and all of it for any PR touching the affected area.
- Tight-budget order. When money runs short, cut in this order: heavy runs first (sample), then nightly full runs on the lowest-traffic engine (to every second night), then desktop engine smoke on PRs, and never the primary-engine full suite on PRs.
Escalation to the full matrix
Escalate a PR (run the nightly set now, or block merge until it passes) when any of these is true. The first three can be checked by a script from the diff and the tool versions alone, so automate them; the last two need a person to look at nightly results or an incident:
- The diff touches the browser support surface: the browserslist file (the project file listing which browsers the code must support), polyfill or transpiler config (a polyfill supplies a feature an older browser lacks; a transpiler rewrites newer syntax into older syntax), global CSS or the design system (the shared library of UI components and styles), or a dependency bump of the UI framework.
- The diff touches code tagged engine-sensitive (forms, inputs, media, layout primitives, newer web APIs).
- The Playwright or browser version changes (the new build is itself a risk).
- A nightly failure appeared on one engine only (the cause may sit in the PR now being merged): run that engine's full suite on the next PRs until it is green.
- A production incident clusters on one platform: add the missing case, and run that platform's full suite on PRs for a period.
How to show the strategy is working
| Measure | What it shows | Good sign |
|---|---|---|
| Escaped browser-specific defects per quarter, by browser | Gaps in coverage | Falling, and no browser has a disproportionate share relative to its traffic |
| Where browser-only defects are found (PR, nightly, release, production) | Shift-left (finding defects earlier in the pipeline) | Most found in PR or nightly |
| Share of sessions covered by PR gates versus traffic | Matrix matches users | Above the agreed bar (for example 90 percent) after each telemetry refresh |
| PR duration at the 90th percentile (the time that 9 in 10 PRs finish within) and cost per PR | The budget holds | Stays inside the budget without growth |
| Escalation precision: escalations that found a bug a smaller run missed, divided by all escalations. If 3 of 12 escalations in a quarter found a bug, precision is 3 / 12 = 25 percent | Triggers are tuned | Not near zero for long (a trigger that never finds anything is noise) |
Review the table monthly. If a browser's escaped defects rise, promote its cases to a higher tier; if an escalation trigger never finds anything for a quarter, drop it.
Pitfalls
- Equal weight to every browser: it burns budget on engines with 1 percent of traffic.
- Smoke subsets that rot: re-pick them from failure history, not from memory.
- Treating emulated mobile as real devices: keep a release gate on real hardware for what emulation cannot see.
- Measuring only pass rate: a green dashboard says nothing about defects that escaped, so track escaped defects per browser alongside it.
Compare running browser tests in containers with Selenium Grid in Docker against using a cloud device farm. Cover reproducibility, parallelisation limits, access to GPUs and real devices, execution latency, CI integration effort and maintenance overhead. Which would you recommend for a small startup and why?
Sample Answer
Direct answer
For a small startup, run browser tests in containers on every PR and rent a cloud device farm for the small set of checks that need real Safari or real phones. If the suite is already written in Selenium, a Selenium Grid in Docker is the container half of that answer; if it is not, use Playwright's own browsers in the same containers and skip the Grid. The reason is cost shape: containers use CI capacity you already pay for and give the fast, reproducible feedback a PR needs, while the one thing containers cannot do is run real Safari or a real device, and a startup should not buy or maintain hardware to cover that small slice. Choose the farm alone only if nobody on the team has time to maintain any test infrastructure at all.
Terms. A container is a lightweight, isolated package of an application and everything it needs, started from an image. Selenium Grid is a server that receives WebDriver commands (the standard remote-control protocol for browsers) and routes each test session to a browser on one of several machines (nodes). In its dynamic mode the Grid starts a fresh container for each session and removes it afterwards. A session is one browser opened by one test, so concurrent sessions are tests running at the same moment. Capabilities are the key-value settings a test sends to say which browser, version and operating system it wants. Docker Compose files are YAML files that describe several containers and how they connect, and Kubernetes is a system that schedules containers across many machines. A cloud device farm is a hosted service that rents real or virtual browsers and phones by the minute or by parallel-session count. Real devices are physical phones.
Comparison
| Axis | Selenium Grid in Docker | Cloud device farm |
|---|---|---|
| Reproducibility | High: the same pinned image runs on a laptop and in CI, so a failure can be replayed locally | Medium: the vendor controls OS and browser patch levels, and updates land on the vendor's schedule; record the version in every report |
| Parallelisation limits | Bounded by your CI machines: plan about 1 CPU per browser container, and the Selenium Docker project adds about 1 more CPU per video-recording container; scale by adding nodes | Bounded by the number of concurrent sessions your plan buys; scaling is a plan change, not an infrastructure task |
| GPUs and real devices | Containers run in headless or virtual-display setups on server CPUs; no real GPU or phone unless you build a lab. The Selenium Docker project publishes Chrome, Firefox and Edge images and its page does not mention Safari, so real Safari is out of reach | Real iPhones, Android phones and macOS Safari are available, which is the main reason to pay |
| Execution latency | Low to start a session (local network, containers close to the code); the dynamic Grid starts a container per session | Higher: a session queue, a network hop to the vendor and a device or VM allocation add time to every session, and the effect is larger the smaller the test |
| CI integration effort | Moderate: write compose or Kubernetes files, size the nodes, set shm_size (the size of the container's shared memory; the project's quick start uses --shm-size=2g per browser container so Chrome does not crash), add video and log collection | Low: point the test at the vendor's remote URL with credentials and capabilities; the vendor supplies video, logs and screenshots |
| Maintenance overhead | Yours: image upgrades, node scaling, cleanup of leaked containers, grid health | The vendor's: new devices and browsers appear without you; you maintain keys, plan sizing, and test-reporting integration |
Recommendation and costs
- Every PR: containerised Chromium and Firefox, plus Playwright's WebKit build if you use Playwright (it is not a Selenium Grid option). That is the fast, deterministic gate, and it costs CI minutes only.
- Nightly and pre-release: a small cloud plan (a few concurrent sessions) running the smoke subset on real Safari on macOS and one real iPhone and one real Android phone. The point is the hardware-only defects, not volume.
- Reassess when: the monthly farm bill exceeds the cost of owning and maintaining a few devices (include the engineer-hours; a lab usually loses for a startup), or the farm's queue time starts to slow releases. Move more of the farm's work into containers if the defects it finds turn out to be reproducible there.
Cost model, showing the break-even shape: let P be the farm plan price per month, c the CI price per hour, h the hours of Grid-backed CI per month, and m the monthly cost of the engineer-hours spent maintaining the Grid. Containers are cheaper than the farm while c x h + m < P.
Worked example with assumed inputs (not vendor quotes): a farm plan with enough concurrent sessions to run the PR suite costs P = 1,200 per month; the CI machines cost c = 1 per hour and run h = 200 hours; maintaining the Grid takes 5 engineer-hours at 60 per hour, so m = 300. Then c x h + m = 200 + 300 = 500, below 1,200, so containers win. If upkeep grows to 20 hours, m = 1,200 and the total is 200 + 1,200 = 1,400, above 1,200, so the farm wins. The break-even upkeep is (1,200 - 200) / 60, about 16.7 hours a month. For a small team m (an engineer's time) tends to dominate, so the usual pattern is containers for volume and a small paid farm for fidelity, not a larger self-hosted Grid.
Pitfalls
- Running every test on the farm: the latency and per-minute cost make PR feedback slow and expensive.
- Expecting Docker to cover Safari: it covers Chromium-based and Gecko-based browsers; Playwright WebKit in Docker is an engine proxy and not iOS or macOS Safari.
- A Grid without video and logs: a failure in a remote container is hard to diagnose; budget storage for artifacts. Note that the Selenium Docker project says video recording is not supported for headless browsers.
- Not pinning image versions, which gives up the reproducibility that was the reason to use containers.
What is headless browser testing, and how can a headless run behave differently from a headed one in ways that change test results? When do you rely on headless in CI, and when do you switch to headed to debug?
Sample Answer
Direct answer
A headless browser is a real browser engine run without a visible window: it still parses HTML, runs JavaScript and lays out and paints the page, but it has no on-screen window and no human at a keyboard. That makes it cheap and scriptable on a CI (continuous integration) server that has no display. It is not guaranteed to behave identically to the headed browser users run, so a green headless run is strong evidence about page logic and a weaker one about anything that depends on the window, the GPU (graphics processor), real input devices or the exact browser build. Use headless for the bulk of every CI run, and switch to headed (visible window, plus the browser's DevTools) when a failure needs to be watched, paused or inspected.
How headless can change a result
Headless differences come from three places: a different browser build, different default environment values, and missing hardware or windowing.
- A different build. Playwright (a test framework that drives real browsers) documents that current releases ship a regular Chromium build for headed runs and a separate "chromium headless shell" for headless runs, and that you can opt into the newer headless mode (the real Chrome browser, more suitable for high-accuracy end-to-end testing) with the
chromiumchannel. That split arrived in Playwright 1.49; the 1.48.2 image used for the probe below predates it. Its install contains a single Chromium build (chromium-1140) and its launcher starts that build with--headless=old, so on 1.48.2 the "default" andchromium-channel projects below run the same binary in the same mode. On 1.49 and later, "headless Chromium" can mean two different binaries, and neither is the Chrome your users install. - Different environment defaults. Anything the page reads from the environment can differ: the default viewport (the visible page area in CSS pixels), whether a pointing device is present, the user-agent string, the pixel ratio (how many physical screen pixels back one CSS pixel; 2 on a typical high-density laptop display, 1 in these containers).
- No real window or GPU. Compositing (the browser combining painted layers into the final image, normally with GPU help), window focus, and native widgets such as the file picker or the print dialog do not behave the way they do on a desktop.
The probe in Running the code was run headless and then headed (under a virtual display, xvfb-run, which gives a headed browser a fake screen on a server) in the Playwright 1.48.2 container. It declares two Chromium projects: chromium-default uses the default launch, and chromium-channel sets channel: 'chromium', which on Playwright 1.49 and later opts into the newer headless mode. On 1.48.2 the two are indistinguishable, as the identical output lines show; rerun the probe after upgrading to see whether they diverge. Three concrete differences appear.
| Observation | Headless | Headed | Test effect |
|---|---|---|---|
Chromium user-agent contains HeadlessChrome | yes (both Chromium projects, measured on 1.48.2) | no | A UA check, a bot filter or an analytics rule can treat the CI browser as a bot |
Firefox matchMedia('(hover: hover)') | false | true | A CSS rule under @media (hover: hover) (for example a hover-only menu) renders differently, so a hover test can pass or fail by mode |
navigator.webdriver | true | true | No difference: this flag is set by automation, not by headlessness |
Reading the probe output below: each line is a project name followed by the values the page read from its own environment. headlessInUA is whether the user-agent string contains HeadlessChrome; webdriver is navigator.webdriver; viewport is the window's inner width x height in CSS pixels (Playwright's default 1280x720 in every mode); hover is whether (hover: hover) matched, meaning the primary pointing device can hover; dpr is the device pixel ratio. Comparing the headless block with the headed block line by line, only headlessInUA (Chromium) and hover (Firefox) change; webdriver, viewport and dpr do not.
The third row matters because it is a common wrong assumption: sites that block automation key off navigator.webdriver and the UA, and headed mode does not hide either.
Two further differences are documented rather than measured here. Playwright's docs state that media codec support varies between Linux, macOS and Windows, so a video test can pass on a Mac and fail in a Linux CI container. They also say that for the closest-to-Safari experience WebKit should be run on macOS, and that Playwright's WebKit is built from WebKit's main branch, ahead of what Apple ships in Safari. Playwright WebKit is therefore a proxy for Safari's engine, not iOS Safari and not Safari itself.
Three situations where results change, and the effect on cross-browser CI
- Rendering and layout. On Playwright 1.49 and later the headless shell is a separate build from the full browser, and headless runs have no real screen, so pixel ratio, scrollbars, fonts available in the container and hover capability (the Firefox row above) can differ from a user's desktop. Effect: a screenshot or layout assertion can differ between a Linux CI container and a developer's Mac, and because each engine has its own differences, one engine can fail where the other two pass.
- GPU compositing. Compositing normally runs on the GPU; a CI container usually has none, so animations,
will-changelayers and canvas or WebGL (the browser's 3D drawing API) code fall back to software rendering. (will-changeis a CSS hint that an element is about to change, so the browser can prepare for it, for example by giving it its own layer to composite.) Effect: timing of animation-end events and frame rates shift, so a timing-sensitive assertion can fail only in CI, and a performance number measured there does not transfer to user devices. - DevTools behaviour. A headed run lets you open the browser's DevTools (element inspector, network panel, console) on the live page and pause on a breakpoint; a headless run has no window to open them in, so you rely on traces, screenshots, videos and console capture instead. Effect: a failure seen only in CI has to be diagnosed from artifacts, so the CI job must save them (trace, screenshot, console log) for each of the three engines.
Common headless drivers and their trade-offs
| Driver | What it gives | Trade-off |
|---|---|---|
| Playwright (Chromium, Firefox, WebKit builds) | One API over three engines, auto-waiting, traces, built-in --headed, --debug, --ui | WebKit is a patched build, not branded Safari or Chrome |
| Puppeteer | Chromium automation over the DevTools protocol, lightweight | No WebKit; fewer cross-browser features |
| Selenium WebDriver (with Chrome, Firefox or Edge in headless mode) | Works with every language and with branded browsers; widely supported by hosted grids | More plumbing and explicit waiting code |
| jsdom or happy-dom (not a browser) | Fastest, runs inside Node | No layout, no paint, no real events: cannot catch rendering or cross-browser bugs, so it is not a substitute for any row above |
When to rely on headless, when to go headed
- Rely on headless in CI for every PR run and nightly run: no display is needed, containers start fast, it parallelises well, and it is deterministic enough for functional assertions. Pin the browser build (the Playwright version pins it) so a browser auto-update never changes results silently.
- Do not trust headless alone for assertions about rendering, hover or focus behaviour, native dialogs, media codecs, or GPU-dependent features. Run those on a headed browser at least nightly (a virtual display is enough), and on real hardware before release.
- Switch to headed to debug: a failure that reproduces headless but you cannot explain. Run it locally with
npx playwright test --headed, step through with--debug(opens the Playwright Inspector), or record a trace (--trace on) and read it afterwards; a trace holds a per-step log, network and console, and an inspectable DOM snapshot, so it often removes the need to rerun at all. - Triage rule: if a test fails headless and passes headed (or the reverse), the first suspect is the mode difference above, not the product. Print the environment (UA, viewport, hover capability) in the failing job to confirm.
Pitfalls
- Treating
--headedlocally as proof the CI failure is fixed: the CI container may differ in viewport, fonts and locale. - Blocking
HeadlessChromein the app or a bot rule and then wondering why CI traffic is rejected.
Running the code
Files: package.json containing { "private": true, "type": "module" }, playwright.config.js, probe.spec.js below. Run inside mcr.microsoft.com/playwright:v1.48.2-jammy:
npm i @playwright/test@1.48.2
npx playwright test # headless
xvfb-run -a npx playwright test --headed # headed on a virtual display
// playwright.config.js
import { defineConfig } from '@playwright/test';
export default defineConfig({
testDir: '.',
workers: 1,
reporter: 'list',
projects: [
{ name: 'chromium-default', use: { browserName: 'chromium' } },
{ name: 'chromium-channel', use: { browserName: 'chromium', channel: 'chromium' } },
{ name: 'firefox', use: { browserName: 'firefox' } },
{ name: 'webkit', use: { browserName: 'webkit' } },
],
});
// probe.spec.js
import { test } from '@playwright/test';
test('environment probe', async ({ page }, info) => {
await page.goto('data:text/html,<title>probe</title><p>hi</p>');
const facts = await page.evaluate(() => ({
headlessInUA: /HeadlessChrome/.test(navigator.userAgent),
webdriver: navigator.webdriver,
viewport: `${innerWidth}x${innerHeight}`,
hover: matchMedia('(hover: hover)').matches,
dpr: devicePixelRatio,
}));
console.log(info.project.name.padEnd(22), JSON.stringify(facts));
});
Output (identical on 10 consecutive runs of each mode):
# headless
chromium-default {"headlessInUA":true,"webdriver":true,"viewport":"1280x720","hover":true,"dpr":1}
chromium-channel {"headlessInUA":true,"webdriver":true,"viewport":"1280x720","hover":true,"dpr":1}
firefox {"headlessInUA":false,"webdriver":true,"viewport":"1280x720","hover":false,"dpr":1}
webkit {"headlessInUA":false,"webdriver":true,"viewport":"1280x720","hover":true,"dpr":1}
# headed under xvfb
chromium-default {"headlessInUA":false,"webdriver":true,"viewport":"1280x720","hover":true,"dpr":1}
chromium-channel {"headlessInUA":false,"webdriver":true,"viewport":"1280x720","hover":true,"dpr":1}
firefox {"headlessInUA":false,"webdriver":true,"viewport":"1280x720","hover":true,"dpr":1}
webkit {"headlessInUA":false,"webdriver":true,"viewport":"1280x720","hover":true,"dpr":1}
Playwright supports multiple browsers. Describe a cross-browser testing strategy with it that minimises duplicate tests while still covering browser-specific behaviour. How do you parameterise tests and manage browser-specific fixtures or capabilities?
Sample Answer
Direct answer
Write each test once, in one set of files, and let Playwright projects decide where it runs. A project is a named configuration (here one per browser engine) that runs the suite with its own settings. Chromium runs everything; Firefox and WebKit run only the tests tagged as engine-sensitive, because app logic that does not touch the browser engine gives the same answer everywhere. Handle browser differences by feature detection inside a fixture (a fixture is a reusable setup value a test asks for by name), and reserve per-browser branches for the few cases where the difference is the thing under test.
Projects and tags decide where a test runs
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';
// Chromium runs every test. Firefox and WebKit run only tests tagged @engine,
// the ones whose result depends on the browser engine rather than app logic.
const engineOnly = /@engine/;
export default defineConfig({
testDir: './tests',
fullyParallel: true,
reporter: 'list',
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'firefox', use: { ...devices['Desktop Firefox'] }, grep: engineOnly },
{ name: 'webkit', use: { ...devices['Desktop Safari'] }, grep: engineOnly },
],
});
- No duplicated tests. The same
tests/directory feeds all three projects. A device descriptor such asdevices['Desktop Firefox']is a ready-made bundle of settings (viewport size, user agent, touch support) that makes a project behave like that device. Tests are not copied per browser. - Engine-sensitive means layout, form controls, storage, input handling, media and any API that engines implement separately. Pure logic (price formatting, reducers) is tagged
@logicand runs on Chromium only. - Per-project filters.
grepon a project limits that project to matching tests. A command-line--grepis applied on top: with this config,--project=firefox --grep "@logic"lists 0 tests and--project=chromium --grep "@logic"lists 1. - Browser-specific capabilities live in the project's
useblock, for example a branded Edge build withchannel: 'msedge'(documented for projects), a mobile project built from a device descriptor with touch enabled, or a differentbaseURLper environment. Keep these out of test bodies.
Fixtures: detect features, do not sniff browsers
// tests/fixtures.ts
import { test as base } from '@playwright/test';
type Caps = { hasDialog: boolean; hasContainerQueries: boolean };
// Feature detection in the page under test, never a check of browserName for logic.
export const test = base.extend<{ caps: Caps }>({
caps: async ({ page }, use) => {
await page.setContent('<p>probe</p>');
const caps = await page.evaluate(() => ({
hasDialog: typeof HTMLDialogElement === 'function',
hasContainerQueries: CSS.supports('container-type: inline-size'),
}));
await use(caps);
},
});
export { expect } from '@playwright/test';
A fixture runs the probe inside the page under test, so a test says "skip when the page cannot do this" and the reason is the missing feature, not the browser's name. A skip keyed on browserName goes stale when an engine ships the feature; a skip keyed on CSS.supports or typeof HTMLDialogElement heals itself. Keep a skip report in CI so a feature that silently disappears from every engine does not turn the whole row into a skip.
Parameterised tests
// tests/cart.spec.ts
import { test, expect } from './fixtures';
const money = (cents: number) => `$${(cents / 100).toFixed(2)}`;
test('@logic totals format as dollars', () => {
expect(money(1999)).toBe('$19.99');
});
// Assigning an impossible calendar date to a date input must leave it empty.
for (const [value, expected] of [['2026-02-29', ''], ['2026-02-28', '2026-02-28']]) {
test(`@engine date input sanitises ${value}`, async ({ page }) => {
await page.setContent('<input id="d" type="date">');
await page.$eval('#d', (el: HTMLInputElement, v) => { el.value = v; }, value);
expect(await page.inputValue('#d')).toBe(expected);
});
}
test('@engine dialog opens modally when supported', async ({ page, caps }) => {
test.skip(!caps.hasDialog, 'no <dialog> in this engine');
await page.setContent('<dialog id="m">hi</dialog>');
await page.$eval('#m', (d: HTMLDialogElement) => d.showModal());
expect(await page.$eval('#m', (d: HTMLDialogElement) => d.open)).toBe(true);
});
test('@engine container query narrows the card', async ({ page, caps }) => {
test.skip(!caps.hasContainerQueries, 'container queries unsupported');
await page.setContent(`<style>
body{margin:0} #w{container-type:inline-size;width:300px}
#c{width:100%} @container (max-width:400px){#c{width:50%}}
</style><div id="w"><div id="c">x</div></div>`);
expect(await page.$eval('#c', (e) => e.getBoundingClientRect().width)).toBe(150);
});
Reading the three listings line by line: in the fixture, base.extend<{ caps: Caps }> declares a new fixture called caps; the code before await use(caps) is setup, the value passed to use is what the test receives, and anything after it would run as teardown. page.evaluate runs the probe inside the browser page and returns the results. In the spec, page.$eval('#d', fn, value) runs fn inside the page on the first element matching #d, with value passed as its second argument, here assigning it to the date input. 2026-02-29 must give '' because 2026 is not a leap year, so that date does not exist and the browser sanitises the assigned value to an empty string. <dialog> is the HTML element for a dialog box, and showModal() opens it modally, meaning the rest of the page is blocked while it is open. test.skip(!caps.hasDialog, reason) ends the test as skipped when the probe found no support. In the container-query test, #w is a 300px-wide container, and the rule @container (max-width:400px) applies when that container is at most 400px wide, so #c becomes 50% of its container's width: 300 x 0.5 = 150.
The for loop over [value, expected] pairs generates one test per data row, so the date-input check is written once and runs twice per engine. The same loop can take a list of viewports or locales.
Run it
Run in the Playwright 1.48.2 image (Chromium 130, Firefox 131, WebKit 18.0, Linux), the per-project test counts were:
chromium: Total: 5 tests in 1 file
firefox: Total: 4 tests in 1 file
webkit: Total: 4 tests in 1 file
npx playwright test then printed 13 passed (5 + 4 + 4), and npx playwright test --repeat-each=10 printed 130 passed, with no failures or skips across those repeats. Running everything on every engine would be 5 x 3 = 15 executions; the tag split saves 2 here.
Why this scales
With the suite sizes of a real product the saving is larger. For 200 tests of which 60 are engine-sensitive, the split runs 140 + 60 x 3 = 320 executions against 200 x 3 = 600 for everything everywhere, which is 46.7 percent fewer.
Trade-offs and pitfalls
- Mis-tagging. A test that depends on the engine but carries
@logicnever runs on Firefox or WebKit. Review the tag in code review, and when a bug escapes on a non-Chromium browser, add the tag to the test that should have caught it. - Playwright WebKit is not Safari. It tracks WebKit main and runs on Linux here, so it cannot show iOS-specific behaviour (touch handling, on-screen keyboard, iOS storage rules). Keep a real-device row for those.
- Do not hide real divergence. If a behaviour is meant to differ per browser, test the expected difference with an explicit per-browser assertion and a comment saying why; do not skip.
Running the code
# in an empty directory with package.json {"type":"module","devDependencies":{"@playwright/test":"1.48.2"}}
# files: playwright.config.ts, tests/fixtures.ts, tests/cart.spec.ts (as above)
docker run --rm --ulimit core=0 -v "$PWD":/src:ro \
mcr.microsoft.com/playwright:v1.48.2-jammy sh -c \
'cp -r /src /w && cd /w && npm i @playwright/test@1.48.2 && \
npx playwright test --project=firefox --list && \
npx playwright test && npx playwright test --repeat-each=10'
Unlock Full Question Bank
Get access to all 22 Cross-Browser and Cross-Platform Testing interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.