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.
Your UI tests are green on Chrome, but several fail on Firefox and Safari. What kinds of rendering, input and event differences between browsers usually cause this, and what quick mitigation would you apply to each?
Sample Answer
Direct answer
When a suite is green on Chrome and red on Firefox and Safari, the cause is usually one of four things: the test hard-codes an assumption that only Chromium satisfies (an exact pixel value, a default font, a focus side effect), the engines really do render or handle input differently, the app uses a feature one engine lacks, or the environment differs. Triage each failure into one of those buckets before touching code, because the mitigation differs: loosen or rewrite the test, normalise the styling, add a fallback in the app, or pin the environment.
Differences that cause failures, and the quick mitigation for each
| Kind | What differs | Quick mitigation |
|---|---|---|
| Rendering: default styles | Each engine ships its own default stylesheet for form controls and body text | Set font: inherit on form controls and an explicit font stack on the page; self-host web fonts so all engines load the same file |
| Rendering: sub-pixel layout | Engines round fractional sizes differently, so an exact === on a measured size fails | Assert with a tolerance, or assert on structure (which row an item landed in) instead of raw pixels |
| Input: typing into form fields | Engines disagree on what a field accepts and what its value reads while text is invalid | Drive input the way the user does, then assert on the validated result or the error message, not on the raw value string |
| Input: native widgets | Date pickers, select popups and file choosers are drawn by the browser, not the page | Set values through the API (fill, selectOption, setInputFiles) rather than clicking inside native UI |
| Events: focus side effects | Whether a click moves focus onto a button varies by browser and OS | Do not assert on focus after a click; focus the element explicitly when the test needs it |
| Events: timing | Animations, transitions and layout settle at slightly different times | Wait for a condition (an element state, a response) instead of a fixed delay |
Evidence from a run
Run in the Playwright 1.48.2 image (Chromium 130.0, Firefox 131.0, WebKit 18.0, on Linux), a probe page printed:
- Sub-pixel width. A sub-pixel size is a fractional CSS pixel such as 33.33px; each engine stores layout sizes on its own fine grid, so the leftover fraction lands differently. Three
flex: 1items in a 100px container reported widths of33.328125for each item in Chromium and WebKit, and33.33332824707031,33.333343505859375,33.33332824707031in Firefox. 100px cannot be split into three equal whole parts, and the engines resolve the remainder differently: Chromium and WebKit report 33.328125, which is exactly 2133/64 (a whole number of 1/64-pixel steps, so three items total 99.984375), while Firefox reports numbers near 33.3333. A test assertingwidth === 33.328125passes on two engines and fails on Firefox.expect(width).toBeCloseTo(33.33, 1)(within 0.05) passes on all three. - Number input.
12e3is a valid number: theeintroduces an exponent, so it means 12 x 10^3 = 12000.validity.badInputis true when the user has typed something the browser cannot convert to a number, and an invalid number field reads as an emptyvalue(""). After clicking an<input type="number">and typing12e3abc, Chromium reportedvalue"12e3"withbadInputfalse (in the same run, typing onlyabcleft Chromium's value""withbadInputfalse, so Chromium discards the letters that cannot be part of a number as they are typed), while Firefox and WebKit reportedvalue""withbadInputtrue (they keep the text in the box, so it is invalid). That is why""and"12e3"differ: one means no usable number, the other a number the engine accepted. A test that reads.valueafter typing sees different strings. Mitigation: type only valid digits when the test is about something else, and test invalid input in a dedicated case that asserts the visible validation message. - Event order on a button click.
pointerdownis the press of a mouse, finger or pen,mousedownis the older mouse-only press event, andfocusfires when the element becomes the target of keyboard input. All three engines loggedpointerdown, mousedown, focus, pointerup, mouseup, click, so ordering of mouse events is not the usual culprit. - Focus on click. MDN documents that whether clicking a button focuses it varies by browser and OS, and that Safari does not focus it, by design. Playwright's Linux WebKit focused the button in the run above, which shows why a green WebKit project does not prove macOS Safari behaviour. A test that asserts
toBeFocused()after a click is a bad test; a keyboard-accessibility test should press Tab or callfocus()itself.
Triage order
- Open the failure's trace (Playwright's recorded timeline of actions, screenshots and page snapshots, opened with
npx playwright show-trace) or screenshot on the failing browser and read the assertion: is it an exact number, a string from a field, or a missing element? - Re-run that single test on that browser alone (
--project=firefoxruns only the Playwright config project named firefox, one browser setup) to rule out interference from parallel tests. - Classify: test assumption (loosen or rewrite), real cross-engine difference (normalise in CSS or code), missing feature (feature detection plus fallback), or environment (fonts, locale, time zone).
- Fix at the cheapest level. Normalising CSS fixes real users as well as the test, so prefer it when the difference is visible to users.
Pitfalls
- Do not skip a test on the failing browser to make CI green without a ticket; the skip hides a possible real bug.
- Playwright WebKit is not iOS Safari. Mobile-only failures need a real device or a cloud device.
Your app has shipped a bug where the order in which scheduled callbacks run differs between Safari and Chrome, and users on one engine saw a broken flow. You want an automated check that guards this across browsers and, where relevant, Node. How would you design it so results are deterministic, what would you assert, and how would you stop timing variability from making the check flaky?
Sample Answer
Direct answer
Do not compare absolute timings, and do not assert an order the specifications leave open. Instead, record every callback into a log of labelled events, wait until all expected labels have arrived (a settle barrier driven by a counter, not a sleep), and assert relative order by index in that log. Split the rules into two groups: guarantees every engine must meet (synchronous code first, microtasks before any timer, equal-delay timers in scheduling order, a microtask queued inside a timer callback running before the next timer) and per-engine expectations for orderings the standards leave open (kept as data in a config object). Run the same page in Playwright's Chromium, Firefox and WebKit projects, repeat each test ten times, and keep the check in CI knowing that Playwright's WebKit build is not real Safari.
Why the orders differ
JavaScript runs on one thread with a microtask queue (promise callbacks, queueMicrotask) that drains completely after each running piece of code, and several task queues (timers, message events, rendering callbacks such as requestAnimationFrame) from which the browser's event loop picks the next task. The HTML specification fixes the microtask rules and the order of timers with equal delays, but it does not require any particular order between different task sources, such as a MessageChannel message versus a setTimeout(fn, 0) timer, or where a requestAnimationFrame callback lands relative to timers. Engines choose their own scheduling there. A flow that accidentally depends on such an order works in one engine and breaks in another, which is the reported bug.
Terms the probe uses. A task source is a category of scheduled work (timers, messages, rendering) that the browser keeps in its own queue. MessageChannel creates two linked ports; posting on one port fires a message event on the other as a separate task. requestAnimationFrame asks the browser to call a function just before the next screen repaint. process.nextTick and setImmediate exist only in Node: nextTick runs a callback as soon as the current operation finishes, before the event loop moves on, and setImmediate runs it in the loop's check phase, after the poll phase that handles I/O. A settle barrier is a counter that starts at the number of callbacks scheduled and resolves a promise when the last one has fired.
A five-line example shows the basic order:
// tiny.mjs
console.log('A: synchronous');
setTimeout(() => console.log('D: timer, delay 0'), 0);
Promise.resolve().then(() => console.log('C: promise callback'));
console.log('B: synchronous');
Run in Node 20.18, it prints A, B, C, D in that order. The two synchronous lines finish first (A, B). When the running code ends, the microtask queue drains, so the promise callback runs (C). Only then does the event loop take the next task, the timer (D), although its delay is 0. The HTML specification gives browsers the same rule: microtasks run when the call stack empties, before the next task. The probe below repeats this with more kinds of callback and checks which parts of the order are guaranteed.
What to log and what to assert
The probe schedules the same work in every environment and logs a label when each callback fires:
// probe.mjs
// Runs in a browser page (via page.evaluate) and in Node. Self-contained on purpose.
export function runProbe() {
return new Promise((resolve) => {
const log = [];
let pending = 0;
const track = (label, schedule) => {
pending++;
schedule(() => {
log.push(label);
if (--pending === 0) resolve(log); // settle barrier: every scheduled callback has fired
});
};
log.push('sync-start');
track('micro-promise', (cb) => Promise.resolve().then(cb));
track('micro-queue', (cb) => queueMicrotask(cb));
track('timeout-a0', (cb) => setTimeout(cb, 0));
track('timeout-b0', (cb) => setTimeout(cb, 0));
track('timeout-c10', (cb) => setTimeout(cb, 10));
// Microtask queued from inside a timer callback: must run before the next timer.
track('timeout-d5', (cb) => setTimeout(() => { Promise.resolve().then(() => log.push('micro-in-d5')); cb(); }, 5));
track('timeout-e5', (cb) => setTimeout(cb, 5));
if (typeof MessageChannel !== 'undefined') {
track('message', (cb) => { const ch = new MessageChannel(); ch.port1.onmessage = () => { ch.port1.close(); cb(); }; ch.port2.postMessage(0); });
}
if (typeof requestAnimationFrame === 'function') track('raf', (cb) => requestAnimationFrame(() => cb()));
if (typeof setImmediate === 'function') track('immediate', (cb) => setImmediate(cb));
if (typeof process !== 'undefined' && process.nextTick) track('nexttick', (cb) => process.nextTick(cb));
log.push('sync-end');
});
}
How track(label, schedule) works: schedule is a function that arranges for its argument to be called later ((cb) => setTimeout(cb, 0)). track adds 1 to pending, then passes schedule a wrapper that logs the label, subtracts 1, and resolves the whole promise when pending reaches 0. The test therefore waits exactly as long as the slowest callback and no longer. Labels that a primitive cannot produce (no MessageChannel in some hosts, no setImmediate in browsers) are simply not scheduled, so one probe file runs everywhere.
The rules live in a second file. invariantFailures returns a list of broken rules, so a failure message names the exact rule; ENGINE_RULES holds the allowed message-versus-timer relation per engine:
// invariants.mjs
// Order rules that every engine must satisfy, plus per-engine rules kept as data.
const at = (log, label) => log.indexOf(label);
// Engines may legitimately disagree about message-channel vs zero-delay timer order.
export const ENGINE_RULES = {
chromium: { messageVsTimeout: ['after'] },
firefox: { messageVsTimeout: ['after'] },
webkit: { messageVsTimeout: ['before', 'after'] },
};
export function invariantFailures(log) {
const fails = [];
const need = (ok, msg) => { if (!ok) fails.push(msg); };
const macro = ['timeout-a0', 'timeout-b0', 'timeout-d5', 'timeout-e5', 'timeout-c10'];
need(at(log, 'sync-end') === at(log, 'sync-start') + 1, 'synchronous code must finish before any callback');
for (const m of ['micro-promise', 'micro-queue']) {
need(at(log, m) > at(log, 'sync-end'), `${m} must run after the synchronous code`);
for (const t of macro) need(at(log, m) < at(log, t), `${m} must run before ${t}`);
}
need(at(log, 'micro-promise') < at(log, 'micro-queue'), 'microtasks run in the order they were queued');
need(at(log, 'timeout-a0') < at(log, 'timeout-b0'), 'equal-delay timers run in scheduling order');
need(at(log, 'timeout-d5') < at(log, 'micro-in-d5') && at(log, 'micro-in-d5') < at(log, 'timeout-e5'),
'a microtask queued inside a timer callback runs before the next equal-delay timer');
return fails;
}
export function messageRelation(log) {
return at(log, 'message') < at(log, 'timeout-a0') ? 'before' : 'after';
}
Why these assertions and not others: each guaranteed rule compares two labels by their position in the log, so machine speed cannot change the verdict. The two 5 ms timers (timeout-d5, timeout-e5) share a delay, so their relative order is fixed by scheduling order; the 10 ms timer is deliberately not compared with them, because two timers with different delays can swap when the page stalls between scheduling them. requestAnimationFrame is only required to come after the synchronous code: its slot among timers varies between runs even inside one engine.
Making it deterministic and non-flaky
- Settle barrier, not a sleep. The probe resolves only when its counter reaches zero, so the test never reads the log early and never waits a fixed time. A hung callback fails by the test timeout rather than silently passing.
- Relative order by index. Compare positions in the log, never durations or timestamps.
- Open orders become data. Where engines legitimately differ, the allowed relations sit in
ENGINE_RULES. If WebKit is seen producing both orders across repeated runs, as it is here, its entry allows both; if an engine is stable, pin its single value so a change in either direction is noticed. - Repeat. Ten repeats per engine surface an order that is only usually true. A rule that fails in one repeat out of ten is a real defect or a rule that was never guaranteed, and either way it should not stay in the suite as written.
- Isolate the page. The page is created fresh with
setContent, with no network and no app code, so the check fails only because of scheduling.
The Playwright project runs the same spec in three engines with ten repeats each:
// playwright.config.mjs
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: '.',
testMatch: 'order.spec.mjs',
repeatEach: 10, // repeat each test 10 times in every project
workers: 1, // one page at a time keeps timer pressure comparable
timeout: 15_000,
reporter: 'line',
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'firefox', use: { ...devices['Desktop Firefox'] } },
{ name: 'webkit', use: { ...devices['Desktop Safari'] } },
],
});
// order.spec.mjs
import { test, expect } from '@playwright/test';
import { runProbe } from './probe.mjs';
import { ENGINE_RULES, invariantFailures, messageRelation } from './invariants.mjs';
test('scheduling order keeps the guaranteed rules', async ({ page, browserName }) => {
await page.setContent('<!doctype html><title>order</title>');
const log = await page.evaluate(runProbe); // resolves only when every callback has fired
expect(invariantFailures(log), log.join(' > ')).toEqual([]);
// rAF only has to come after the synchronous code; its slot among timers is not asserted.
expect(log.indexOf('raf')).toBeGreaterThan(log.indexOf('sync-end'));
// Engine-specific expectation, read from data rather than hard-coded in the test.
expect(ENGINE_RULES[browserName].messageVsTimeout).toContain(messageRelation(log));
});
The same probe runs in Node, where it also proves the rule set can fail, by feeding it a doctored log in which a timer jumped ahead of a microtask:
// node-run.mjs
import { runProbe } from './probe.mjs';
import { invariantFailures } from './invariants.mjs';
const log = await runProbe();
console.log(log.join(' > '));
console.log('failures:', invariantFailures(log));
// Teeth check: a doctored log where a timer jumped ahead of a microtask must be reported.
const bad = log.filter((l) => l !== 'timeout-a0');
bad.splice(bad.indexOf('micro-promise'), 0, 'timeout-a0');
console.log('doctored log failures:', invariantFailures(bad));
The last four lines of node-run.mjs exist because a rule set that has never failed has not been shown to work. They edit the real log so a timer jumps ahead of a microtask and require invariantFailures to report it.
Worked result
Run in the Playwright 1.48.2 image (Chromium 130.0, Firefox 131.0, WebKit 18.0, Node 20.18, probe loaded as an ES module), node node-run.mjs printed:
sync-start > sync-end > micro-promise > micro-queue > nexttick > immediate > timeout-a0 > timeout-b0 > message > timeout-d5 > micro-in-d5 > timeout-e5 > timeout-c10
failures: []
doctored log failures: [
'micro-promise must run before timeout-a0',
'micro-queue must run before timeout-a0'
]
npx playwright test reported 30 passed (3 engines x 10 repeats) on each of three consecutive invocations. In separate exploratory loops on the same page, the observed logs showed what the config encodes: Chromium and Firefox put message after timeout-a0 in every observed run, WebKit sometimes put message first, and raf appeared at different slots from run to run in all three engines, which is why it has no position rule. Node-only labels (nexttick, immediate) are logged but not asserted; they are absent from the browser rules and their placement relative to promise callbacks is an environment detail the guard does not depend on.
Reading the Node log label by label:
sync-start,sync-end: the probe function runs to its end first; everything else was only queued.micro-promise,micro-queue: the microtask queue drains in the order the callbacks were queued, before any timer.nexttickcomes after the promise callbacks here, which can look backwards becausenextTickis described as running first. Node's documentation explains it: in a CommonJS file the next-tick queue runs before promise callbacks, but an ES module is processed as part of the microtask queue, so Node is already draining microtasks and the promise callbacks go first.probe.mjsis an ES module. The same three lines show both orders:
// ticks.cjs (the same three lines are saved as ticks.mjs)
Promise.resolve().then(() => console.log('promise'));
process.nextTick(() => console.log('nextTick'));
console.log('sync');
Run in Node 20.18, ticks.cjs prints sync, nextTick, promise, and ticks.mjs prints sync, promise, nextTick.
4. immediate precedes timeout-a0. Node's event-loop guide says that when setTimeout(fn, 0) and setImmediate are both called from the main module, the order is non-deterministic and depends on the performance of the process. That is why the probe records immediate and asserts nothing about it.
5. timeout-a0, timeout-b0: equal delays run in scheduling order, a guaranteed rule.
6. message lands between timeout-b0 and timeout-d5. Node delivers message ports through its own machinery, so this slot is a Node detail. The specifications do not order a message task against timers, which is why the browser projects check it against ENGINE_RULES and not against a fixed position.
7. timeout-d5, micro-in-d5, timeout-e5: the d5 callback queued a promise callback, and the microtask queue drains straight after that callback, before the next timer is taken.
8. timeout-c10 is last only because nothing stalled; it is not compared with the 5 ms timers.
If you keep only two rules from this, keep these: synchronous code finishes before any callback, and every queued microtask runs before the next timer or message task. The other assertions follow from the same two ideas.
What the guard does not prove
Playwright's WebKit is a build of the WebKit engine running on Linux, not Safari on iOS or macOS, so it can miss behaviour that comes from Safari's own scheduling or from iOS itself. Keep the production bug as a regression case here (it catches engine-level scheduling), and add a small real-Safari check on a cloud device or a macOS runner for the specific flow that broke, before relying on this alone. Also fix the app: the durable remedy is that the flow stops depending on an order the specifications leave open, for example by chaining promises or awaiting an explicit completion signal instead of racing a timer against a message.
Running the code
# put the files above in an empty folder (ticks.cjs and ticks.mjs hold the same three lines)
echo '{"type":"module"}' > package.json
docker run --rm --ulimit core=0 -v "$PWD":/w -w /w mcr.microsoft.com/playwright:v1.48.2-jammy \
sh -c 'timeout 200 sh -c "npm i --no-audit --no-fund @playwright/test@1.48.2 && node tiny.mjs && node ticks.cjs && node ticks.mjs && node node-run.mjs && npx playwright test"'
A teammate has just built a new responsive component and asks you to confirm it works across screen sizes, browsers and devices before it ships. Walk me through how you would verify it, where browser emulation is good enough and where you need real devices, and how you would decide which viewports and platforms get coverage first.
Sample Answer
Direct answer
Verify the component in layers, cheapest first. (1) Resize it in the browser and in DevTools device mode, and run an automated check across the three browser engines (Chromium, Firefox and WebKit, the engine behind Safari) at a handful of widths. (2) Inspect what emulation cannot show on a few real phones or cloud-hosted real devices. (3) Choose coverage by risk and real traffic, not by a device list. Emulation is good enough for layout logic: breakpoints (the widths where CSS changes the layout), wrapping, overflow and keyboard order. You need a real device for anything that depends on the actual mobile browser, the touch hardware or the operating system: iOS Safari's collapsing address bar and viewport units, the on-screen keyboard resizing the page, real font rendering, momentum scrolling (scrolling that keeps gliding after the finger lifts) and genuine touch gestures.
Step 1: Verify layout in emulation and in three engines
- Resize by hand first. Drag the window from 320 CSS px (CSS pixels, the browser's logical pixels, not device hardware pixels) up to 1440 and watch for horizontal scrollbars, clipped text, overlapping items and awkward gaps between breakpoints. Most responsive bugs live between the named breakpoints, not at them.
- Use DevTools device mode for fast iteration. Chrome documents it as a "first-order approximation" of a mobile device: it simulates viewport size, pixel ratio, touch input and CPU and network throttling, but it does not run the page on a mobile device, and the docs say there are aspects of mobile devices DevTools will never simulate (Chrome DevTools: device mode). That one sentence is the dividing line for the whole answer.
- Automate the layout rules so the check runs on every pull request in all three engines. The test below renders the component at 320, 375, 768 and 1280 px and asserts the number of grid columns, that there is no horizontal overflow, that every button is at least 44 by 44 CSS px, and that the Tab key visits each card in order. The projects include Playwright's
Pixel 5andiPhone 13device descriptors, which set viewport, user agent and touch support. The iPhone descriptor runs Playwright's WebKit build, which is not iOS Safari: it is the same engine family on Linux with an iPhone-sized viewport, so it catches engine-level layout differences but not iOS-specific browser behaviour.
The component is a card grid whose columns come from repeat(auto-fit, minmax(240px, 1fr)), so it needs no media query. In plain words: make as many columns as fit, each at least 240 px wide, and let the columns share leftover space equally (1fr is one equal share). A narrow screen therefore gets one column and a wide one gets more, with no breakpoint in the CSS:
// card-grid.mjs
export const html = `<!doctype html><meta name="viewport" content="width=device-width, initial-scale=1"><title>cards</title>
<style>
body { margin: 0; padding: 16px; font: 16px system-ui, sans-serif; }
.grid { display: grid; gap: 16px; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); }
.card { border: 1px solid #888; padding: 12px; min-width: 0; overflow-wrap: anywhere; }
.card button { min-height: 44px; min-width: 44px; padding: 0 16px; font: inherit; }
.card button:focus-visible { outline: 3px solid #05f; }
</style>
<main class="grid">
${[1, 2, 3, 4, 5].map((i) => `<article class="card"><h2>Card ${i}</h2><p>averyveryverylongunbrokenorderidentifier-${i}-0123456789abcdef0123456789abcdef</p><button>Open</button></article>`).join('')}
</main>`;
// playwright.config.mjs
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: '.',
testMatch: 'card-grid.spec.mjs',
workers: 1,
timeout: 20_000,
reporter: 'list',
projects: [
{ name: 'desktop-chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'desktop-firefox', use: { ...devices['Desktop Firefox'] } },
{ name: 'desktop-webkit', use: { ...devices['Desktop Safari'] } },
{ name: 'pixel-5', use: { ...devices['Pixel 5'] } }, // Chromium with mobile emulation
{ name: 'iphone-13', use: { ...devices['iPhone 13'] } }, // WebKit with iPhone viewport, UA and touch
],
});
// card-grid.spec.mjs
import { test, expect } from '@playwright/test';
import { html } from './card-grid.mjs';
const WIDTHS = [320, 375, 768, 1280];
// Expected columns for repeat(auto-fit, minmax(240px, 1fr)): body padding 16 + 16, gap 16.
const expectedColumns = (w) => Math.floor((w - 32 + 16) / (240 + 16));
for (const width of WIDTHS) {
test(`grid holds at ${width}px`, async ({ page }, info) => {
await page.setViewportSize({ width, height: 800 });
await page.setContent(html);
const m = await page.evaluate(() => {
const grid = document.querySelector('.grid');
const cols = getComputedStyle(grid).gridTemplateColumns.split(' ').length;
const btn = document.querySelector('button').getBoundingClientRect();
return {
cols,
overflowX: document.documentElement.scrollWidth - document.documentElement.clientWidth,
btnW: Math.round(btn.width), btnH: Math.round(btn.height),
coarse: matchMedia('(pointer: coarse)').matches,
hoverNone: matchMedia('(hover: none)').matches,
};
});
console.log(`${info.project.name} ${width}px cols=${m.cols} overflowX=${m.overflowX} button=${m.btnW}x${m.btnH} coarse=${m.coarse} hoverNone=${m.hoverNone}`);
expect(m.cols).toBe(expectedColumns(width));
expect(m.overflowX).toBeLessThanOrEqual(0); // no horizontal scrollbar
expect(m.btnH).toBeGreaterThanOrEqual(44); // house target; WCAG 2.2 AA minimum is 24
expect(m.btnW).toBeGreaterThanOrEqual(44);
});
}
test('keyboard reaches every button in order', async ({ page, browserName }) => {
await page.setContent(html);
const seen = [];
for (let i = 0; i < 5; i++) {
await page.keyboard.press('Tab');
seen.push(await page.evaluate(() => document.activeElement.closest('.card')?.querySelector('h2').textContent));
}
console.log(`${browserName} tab order: ${seen.join(', ')}`);
expect(seen).toEqual(['Card 1', 'Card 2', 'Card 3', 'Card 4', 'Card 5']);
});
The test prints three values per width that need a key. overflowX is the page's scrollable width minus its visible width; 0 means no horizontal scrollbar. coarse is whether the media query (pointer: coarse) matches, meaning the main input is imprecise, such as a finger. hoverNone is whether (hover: none) matches, meaning the main input cannot hover, as with touch. WCAG is the Web Content Accessibility Guidelines, and AA is its middle conformance level. A :focus-visible style is applied when the browser decides a focus ring helps the user, typically after keyboard focus.
The expected column count is computed, not guessed. N columns need N x 240 px plus (N - 1) gaps of 16 px, and the available width is W - 32, so N fits when N x 240 + (N - 1) x 16 <= W - 32, which rearranges to N <= (W - 32 + 16) / (240 + 16). With 16 px body padding on each side and a 16 px gap, the usable width is W - 32 and the number of 240 px columns that fit is floor((W - 32 + 16) / (240 + 16)): 320 px gives floor(304 / 256) = 1, 375 gives floor(359 / 256) = 1, 768 gives floor(752 / 256) = 2, and 1280 gives floor(1264 / 256) = 4 (four columns need 4 x 240 + 3 x 16 = 1,008 px of the 1,248 available, and five would need 1,264). Run in the Playwright 1.48.2 container (Chromium 130, Firefox 131, WebKit 18.0), all 25 tests pass (5 projects x 4 widths = 20 layout tests, plus one Tab-order test per project) and the log prints one line for each of them; 8 lines are excerpted here, and every omitted test is held to the same assertions:
desktop-chromium 320px cols=1 overflowX=0 button=72x44 coarse=false hoverNone=false
desktop-chromium 768px cols=2 overflowX=0 button=72x44 coarse=false hoverNone=false
desktop-chromium 1280px cols=4 overflowX=0 button=72x44 coarse=false hoverNone=false
desktop-firefox 320px cols=1 overflowX=0 button=72x44 coarse=false hoverNone=true
desktop-webkit 320px cols=1 overflowX=0 button=74x44 coarse=false hoverNone=false
pixel-5 320px cols=1 overflowX=0 button=72x44 coarse=true hoverNone=true
iphone-13 1280px cols=4 overflowX=0 button=74x44 coarse=true hoverNone=true
chromium tab order: Card 1, Card 2, Card 3, Card 4, Card 5
25 passed (4.1s)
Two details in that output are exactly why real checks beat assumptions. The button is 72 px wide in Chromium and Firefox but 74 px in WebKit: the same CSS produces a slightly different size because each engine lays out text differently. And headless Firefox in this image reports (hover: none) as true on a desktop viewport, while headless Chromium and WebKit report false: any hover-only affordance (a menu that opens only on :hover) has to be guarded with @media (hover: hover) and tested in more than one engine rather than assumed.
Step 2: Where emulation is enough and where a real device is needed
| Concern | Emulation (DevTools, Playwright descriptors) | Real device or cloud real device |
|---|---|---|
| Breakpoints, wrapping, overflow, grid columns | Enough | Spot check only |
| Touch target size, keyboard Tab order, focus ring | Enough for size and order | Check the focus ring and a real thumb reach |
| Pointer and hover media queries | Partly: descriptors set touch support, but defaults differ per engine as shown above | Confirm hover-only UI degrades |
iOS Safari address bar, 100vh vs 100dvh, safe-area insets (notch and home-indicator space) | Not reproduced | Needed |
| On-screen keyboard covering a focused input or fixed footer | Not reproduced | Needed |
| Real font rendering, device pixel ratio artefacts, GPU-dependent effects | Approximated | Needed |
| Scroll momentum, pinch zoom, multi-touch gestures, performance on a slow phone | Throttling only (CPU and network) | Needed |
Run the real-device pass as a short, scripted spot check, not a full regression: the three or four interactions that differ on phones (open, scroll, type in a field, rotate) on one recent iPhone and one mid-range Android phone. A cloud device farm (a service that rents you real phones over the network) is the right tool if the team owns no devices, because the spot check is a handful of minutes per release.
Step 3: Decide which viewports and platforms come first
Rank by traffic times risk, using the product's own analytics rather than a generic list:
- Pull the last 30 to 90 days of sessions by browser, operating system and viewport width from the analytics tool. Cover the combinations that make up the top share of sessions first.
- Add risk: any engine where the component uses a feature with known gaps (container queries,
dvhunits,:has()), and always include WebKit because WebKit is the engine behind Safari on iPhone. - Pick three widths that sit just inside breakpoint edges (for example 320 as the narrowest realistic phone, one width just under the tablet breakpoint, one just over) plus a wide desktop, not every device size.
- Run the fast set (the three engines at those widths) on every pull request and the real-device spot check before release.
Commit to this default: three engines at four widths on every pull request, real devices at release, and re-rank the list each quarter from fresh traffic data. It flips toward heavier real-device coverage when the component is touch-first (a swipe carousel, a drag handle), handles text entry near the screen bottom, or the traffic is mostly mobile.
Touch targets and keyboard use
The test above already asserts 44 by 44 CSS px for the button. That is the team's own target, deliberately larger than the WCAG 2.2 AA minimum (Success Criterion 2.5.8, Target Size Minimum), which requires pointer targets of at least 24 by 24 CSS px unless a spacing, equivalent-control, inline, user-agent or essential exception applies (W3C: Target Size (Minimum)). For the keyboard, the Tab order test proves every control is reachable in visual order, and :focus-visible gives a ring only for keyboard users. Do the rest of the accessibility audit (screen readers, contrast) as its own pass.
Pitfalls
- Treating "it looks right in the Chrome device toolbar" as cross-browser evidence: it is one engine.
- Using Playwright's
iPhone 13run as proof of iOS Safari behaviour. It is WebKit with an iPhone-shaped viewport. - Testing only at named breakpoints, so the bug at 600 to 700 px is never seen.
- Choosing devices by what the team owns instead of what visitors use.
Running the code
# in an empty folder holding the three files above
echo '{"type":"module"}' > package.json
docker run --rm --ulimit core=0 -v "$PWD":/w -w /w mcr.microsoft.com/playwright:v1.48.2-jammy \
sh -c 'timeout 200 sh -c "npm i --no-audit --no-fund @playwright/test@1.48.2 && npx playwright test"'
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}
Screenshots of the same page differ between Windows and macOS because of font smoothing and display DPI. How do you keep these platform rendering differences from causing false failures while still catching real regressions, and how do you maintain baselines when an OS or font update shifts rendering?
Sample Answer
Direct answer
Do not compare pixels across operating systems. Pick one pinned environment (a Linux container image with a fixed browser build and fonts) as the only place pixel baselines are created and compared, and run it everywhere through that same image, including on developers' Macs and Windows machines. On native Windows and macOS runners, run the same journeys with geometry and behaviour assertions instead of pixel baselines. When an OS, browser or font update shifts rendering, treat it as an environment change: refresh every baseline in one dedicated change, reviewed by eye, while the geometry tests stay green and prove nothing real moved.
Playwright's own guidance says why: browser rendering varies with the host OS, version, settings, hardware, power source and headless mode, so screenshots must be compared in the environment that produced the baseline. A visual test stores a baseline, the reference screenshot saved in the repository from a known-good run, and each later run takes a new screenshot and compares it with that baseline. A screenshot compares pixels; font smoothing (how glyph edges are anti-aliased, meaning partly shaded with intermediate colours so curves look smooth) and display DPI (device pixels per CSS pixel) change pixels without changing what the user can do.
Step 1: Remove the noise you control
| Source of false failures | Control |
|---|---|
| Device pixel ratio differs between machines | Fix deviceScaleFactor (Playwright's name for device pixels per CSS pixel) and the viewport in the config. The run below shows ratio 1 and 2 give 360x132 and 720x264 images, which can never match |
font-family: sans-serif resolves to a different installed font per OS | Ship the fonts with the app (@font-face with woff2 files, a compressed web font format) and wait for document.fonts.ready before capturing |
| Animations, carets, loading spinners | toHaveScreenshot (Playwright's assertion that compares a screenshot with the stored baseline) defaults to animations: "disabled" and caret: "hide"; mask or hide the rest |
| Dates, avatars, ads, counters | mask: [locator] (paints a solid box) or stylePath (a CSS file injected only while the screenshot is taken) to hide them, or mock the data |
| A whole-page capture dilutes a real change | Screenshot the component, so a change is a large share of the pixels |
Step 2: Choose tolerances from measurements, not from taste
pixelmatch is the small open-source library that counts differing pixels between two images; Playwright's comparison works the same way. It decides a match with a per-pixel colour threshold (default 0.2 on a 0 to 1 scale) and then a budget of different pixels (maxDiffPixels or maxDiffPixelRatio). The script below captures the same 360x132 card region in several states and counts differing pixels. Rendering the text with text-rendering: geometricPrecision is a stand-in for a different rasteriser (the part of an operating system that turns glyph outlines into pixels; the Windows and macOS text engines cannot be run in this environment); real cross-OS noise must be measured the same way on your own runners.
// noise.mjs
import { chromium } from 'playwright';
import { PNG } from 'pngjs';
import pixelmatch from 'pixelmatch';
const page_html = (css = '') => `<style>
body { font: 16px/1.4 sans-serif; margin: 16px; }
#card { width: 360px; }
h1 { font-size: 28px; margin: 0 0 8px; }
button { padding: 8px 16px; font: inherit; background: #0a6; color: #fff; border: 0; border-radius: 4px; }
${css}
</style><div id="card"><h1>Order summary</h1><p>3 items, total $42.50</p><button>Pay now</button></div>`;
const browser = await chromium.launch();
async function shot(css, deviceScaleFactor = 1) {
const ctx = await browser.newContext({ viewport: { width: 400, height: 200 }, deviceScaleFactor });
const page = await ctx.newPage();
await page.setContent(page_html(css));
await page.evaluate(() => document.fonts.ready); // fonts settled before the capture
const png = PNG.sync.read(await page.screenshot({ animations: 'disabled', clip: { x: 16, y: 16, width: 360, height: 132 } }));
await ctx.close();
return png;
}
const diff = (a, b) => {
if (a.width !== b.width || a.height !== b.height) return `size mismatch ${a.width}x${a.height} vs ${b.width}x${b.height}`;
const n = pixelmatch(a.data, b.data, null, a.width, a.height, { threshold: 0.2 });
return `${String(n).padStart(5)} px differ (${(100 * n / (a.width * a.height)).toFixed(3)}% of ${a.width * a.height})`;
};
const base = await shot('');
// Every capture is the same 360x132 region the card test below compares, so ratios share one basis.
const cases = {
'same page rendered twice': await shot(''),
'text-rendering: geometricPrecision': await shot('body { text-rendering: geometricPrecision; }'),
'text colour #222 -> #2a2a2a': await shot('body { color: #2a2a2a; }'),
'button padding 8px -> 12px': await shot('button { padding: 12px 16px; }'),
'heading font sans -> serif': await shot('h1 { font-family: serif; }'),
'button colour #0a6 -> #c33': await shot('button { background: #c33; }'),
'device scale factor 1 -> 2': await shot('', 2),
};
const baseDark = await shot('body { color: #222; }');
for (const [name, png] of Object.entries(cases)) {
const ref = name.startsWith('text colour') ? baseDark : base;
console.log(name.padEnd(38), diff(ref, png));
}
await browser.close();
How to read noise.mjs. shot(css, deviceScaleFactor) opens a fresh browser context, loads the card with the extra CSS, waits for fonts, and returns the pixels of one fixed 360x132 rectangle (clip), so every capture has the same size and a pixel count is comparable. diff returns a size mismatch if the images differ in size, otherwise the number of differing pixels and that number as a percentage of the 47,520 pixels (360 x 132). The text colour case uses baseDark, a baseline whose body text is explicitly #222, because the page's default text is black and comparing black against #2a2a2a would measure a different change from the one in the row; with #222 as the reference only the 0x22 to 0x2a drift is measured. The device-scale case is a size mismatch because at ratio 2 the same clip is 720x264 pixels.
The test setup that proves the configuration end to end (a card component compared with a baseline, plus a geometry test that needs no baseline):
// playwright.config.mjs
import { defineConfig } from '@playwright/test';
export default defineConfig({
testMatch: 'visual.spec.mjs',
reporter: 'line',
// Compare small components, not whole pages, so a real change is a large share of the pixels.
expect: { toHaveScreenshot: { maxDiffPixelRatio: 0.005, threshold: 0.2 } },
use: { viewport: { width: 400, height: 240 }, deviceScaleFactor: 1 },
projects: [{ name: 'chromium', use: { browserName: 'chromium' } }],
});
// visual.spec.mjs
import { test, expect } from '@playwright/test';
const card = (padding) => `<style>
body { font: 16px/1.4 sans-serif; margin: 16px; }
#card { width: 360px; }
h1 { font-size: 28px; margin: 0 0 8px; }
button { padding: ${padding}; font: inherit; background: #0a6; color: #fff; border: 0; border-radius: 4px; }
</style><div id="card"><h1>Order summary</h1><p>3 items, total $42.50</p><button>Pay now</button></div>`;
test('card pixels', async ({ page }) => {
await page.setContent(card(process.env.REGRESS ? '12px 16px' : '8px 16px'));
await page.evaluate(() => document.fonts.ready);
await expect(page.locator('#card')).toHaveScreenshot('card.png');
});
test('card layout holds on any OS', async ({ page }) => {
await page.setContent(card('8px 16px'));
const cardBox = await page.locator('#card').boundingBox();
const button = await page.locator('button').boundingBox();
expect(cardBox.width).toBe(360);
expect(button.x + button.width).toBeLessThanOrEqual(cardBox.x + cardBox.width);
expect(await page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth)).toBe(true);
});
steps.sh runs the four stages of a baseline's life. Its clean function is a sed filter that deletes two things: the terminal control codes the line reporter writes (it moves the cursor up and erases a line, which on a real terminal would wipe the line above the count), and the per-test timing such as (1.2s), so the output is the same on every run. grep -E then keeps only the lines that matter: the missing-snapshot error, the pass and fail counts, and the comparison failure. --update-snapshots writes or overwrites the baseline files. The geometry test (card layout holds on any OS) asserts positions and sizes from boundingBox() and so needs no baseline; these are the geometry assertions the direct answer refers to.
# steps.sh
# clean() removes terminal control codes (the line reporter erases lines with them) and per-test timings such as " (1.2s)".
clean() { sed -E 's/\x1b\[[0-9;]*[A-Za-z]//g; s/ \([0-9.]+m?s\)//'; }
rm -rf visual.spec.mjs-snapshots test-results
echo "$ npx playwright test # no baseline yet"
npx playwright test 2>&1 | clean | grep -E "snapshot doesn|passed|failed"
echo "$ npx playwright test --update-snapshots"
npx playwright test --update-snapshots 2>&1 | clean | grep -E "passed|failed"
echo "$ npx playwright test"
npx playwright test 2>&1 | clean | grep -E "passed|failed"
echo "$ REGRESS=1 npx playwright test # button padding 8px -> 12px"
REGRESS=1 npx playwright test 2>&1 | clean | grep -E "^ +Expected an image|passed|failed"
Run in the Playwright 1.48.2 container (Chromium, Linux), the output is identical on each of 10 runs:
same page rendered twice 0 px differ (0.000% of 47520)
text-rendering: geometricPrecision 179 px differ (0.377% of 47520)
text colour #222 -> #2a2a2a 0 px differ (0.000% of 47520)
button padding 8px -> 12px 202 px differ (0.425% of 47520)
heading font sans -> serif 710 px differ (1.494% of 47520)
button colour #0a6 -> #c33 3198 px differ (6.730% of 47520)
device scale factor 1 -> 2 size mismatch 360x132 vs 720x264
$ npx playwright test # no baseline yet
Error: A snapshot doesn't exist at /w/visual.spec.mjs-snapshots/card-chromium-linux.png, writing actual.
1 failed
1 passed
$ npx playwright test --update-snapshots
2 passed
$ npx playwright test
2 passed
$ REGRESS=1 npx playwright test # button padding 8px -> 12px
Error: Screenshot comparison failed:
Expected an image 360px by 132px, received 360px by 140px. 932 pixels (ratio 0.02 of all image pixels) are different.
1 failed
1 passed
Reading it:
- The tolerance
maxDiffPixelRatio: 0.005(0.5%) accepts the rasteriser stand-in (0.377%) and a tiny colour drift (#222to#2a2a2a, 0 differing pixels because it is under the 0.2 per-pixel threshold), and rejects the font swap (1.494%) and the colour change (6.730%). - Changing the button's vertical padding from 8px to 12px adds 4 pixels above and 4 below, so the card grows by 8 pixels (132 to 140). Inside the fixed 360x132 region that
noise.mjsclips it differs by only 0.425% (202 of 47,520 pixels), below the 0.5% budget, so a ratio alone would let it through. The Playwright test screenshots the element itself, which is now 360x140 = 50,400 pixels, and 932 of them differ (932 / 50,400 = 1.8%, shown by Playwright as ratio 0.02), which is why that figure is larger than 0.425%. It fails because the height changed from 132 to 140 pixels and a size mismatch is a failure regardless of tolerance (raisingmaxDiffPixelRatioto 0.9 still fails it with the same size message). The lesson is that a ratio budget cannot separate noise from small shifts when they overlap, so tighten the environment (fewer noise sources) and keep geometry assertions for layout. - The first run with no baseline fails and writes one named
card-chromium-linux.png; Playwright names snapshots by browser and platform (documented), so a Mac run would look for-darwinand find nothing.
Step 3: Cover native Windows and macOS without false failures
- Run the geometry test (card width, button inside card, no horizontal overflow, as in
visual.spec.mjs) on the native runners, plus assertions on computed styles. It is a pass or fail on layout, not on anti-aliasing. - If a page really needs a native pixel check (OS-styled form controls, a platform font fallback), keep a separate small set of baselines per platform, a handful of components not the whole suite, so each file name carries the platform.
- Run the pixel suite for developers through the container image (
docker run ... mcr.microsoft.com/playwright:v1.48.2-jammy), so a Mac developer produces-linuxbaselines identical to CI.
Step 4: Maintaining baselines when an OS or font update shifts rendering
- Pin the image tag (or digest) and the browser version; update them only in a dedicated change.
- In that change run
npx playwright test --update-snapshotsinside the new image and commit only the changed PNGs and the pin, with no source changes, so every difference is attributable to the environment. - Review the diff images: expect text edges to move; reject any change that moves layout or content. The geometry tests must pass on the new image before the refresh is accepted.
- Merge the image pin and baselines together so the main branch is never red, and delete baselines for tests that no longer exist.
- Treat an unexpectedly large changed set as a signal to investigate the environment (a missing font) before approving.
Pitfalls
Raising the tolerance until the cross-OS failures stop also hides real regressions; the run above shows an 8-pixel growth in height measuring only 0.425% in a fixed region, inside a 0.5% budget. Whole-page screenshots, unmasked timestamps and system font stacks are the common sources of false failures.
Running the code
# files above in one folder, plus {"type":"module"} in package.json, then:
docker run --rm --ulimit core=0 -v "$PWD":/w -w /w mcr.microsoft.com/playwright:v1.48.2-jammy sh -c \
'npm i --silent playwright@1.48.2 @playwright/test@1.48.2 pngjs@7.0.0 pixelmatch@5.3.0 && timeout 200 sh -c "node noise.mjs; sh steps.sh"'
Unlock Full Question Bank
Get access to all 15 Cross-Browser and Cross-Platform Testing interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.