Headless Chrome testing gotchas
headless-chromecdptestingscreenshotswebgl
Driving headless Chrome (over the DevTools protocol or with --screenshot / --dump-dom) is the main way UI claims get verified on Justin's projects. It is also easy to get a test that silently proves nothing. Each item below has produced at least one wrong conclusion; most look like a product bug when they are really a test artifact.
Starting it
- Typical launch:
google-chrome --headless=new --remote-debugging-port=NNNN --user-data-dir=<scratch> --no-first-run --disable-gpu, then talk to it with Node's built-inWebSocket(Node 22+) or Pythonaiohttp. No puppeteer is installed on the desktop. - For WebGL (three.js viewers, shader pages) add
--use-gl=angle --use-angle=swiftshader --enable-unsafe-swiftshader. A plain screenshot of a WebGL page without CDP:google-chrome --headless=new --enable-unsafe-swiftshader --use-angle=swiftshader --virtual-time-budget=15000 --screenshot=out.png <url>. --screenshot=x.jpgwrites a JPEG because of the extension, which is handy for thumbnails when PIL is not available.--enable-logging=stderrand grep forCONSOLEshows page errors (this is how a shader variable namedfshadowing a formatter functionf()was found, which had killed the whole page).
Things that silently invalidate a test
- Headless reports
hover: none.matchMedia('(hover: none)').matchesis true even at desktop width with touch emulation off, so code takes the touch branch.Emulation.setEmulatedMediawith ahoverfeature does not change it. OverridematchMediabefore page scripts run withPage.addScriptToEvaluateOnNewDocument, returning{matches:false, ...}for that one query.:hoverstyles needCSS.forcePseudoState. Corollary: anything hidden by(hover: hover) and (pointer: fine)cannot be asserted headlessly. Element.click()is not a user gesture. It dispatches an untrusted event with no transient activation, so unmutedplay()andrequestFullscreen()fail and the test "proves" a bug. UseInput.dispatchMouseEvent(pressed + released) orInput.dispatchTouchEvent(start + end). Touch dispatch also exercises the compatibility mouse events, where real bugs live (see Touch compatibility mouse events (mousemove before click)).scroll-behavior: smoothmoves the target after you measure it. A rect read right afterscrollIntoView()is where the element was. Setdocument.documentElement.style.scrollBehavior = 'auto'or wait ~900 ms, and sanity-check withdocument.elementFromPoint(x, y).- Emulated mobile uses the desktop autoplay policy. An unmuted autoplay under
setDeviceMetricsOverride({mobile:true})proves nothing about a real phone. Say so. - Minimum window width.
--window-size=390,844does not give a 390 px viewport; Chrome enforces a minimum (~500 px wide, ~757 tall) and crops the screenshot, which looks like horizontal overflow. Measure phone layouts inside a sized<iframe>(390 to 412 px) or useEmulation.setDeviceMetricsOverride. ProbescrollWidth == clientWidthin the game document itself; a scrollbar in the screenshot may belong to the outer page. captureBeyondViewport: truepaintsposition: fixedlayers once at the top, so a full-page shot makes a fixed background look like it stops. Judge fixed layers from viewport-sized shots.- Virtual time. Under
--virtual-time-budget:performance.now()does not advance (a timing assertion passes at 0.0 ms), rAF barely fires (and is starved inside iframes), Web Workers are not waited for, and CSS transitions in an iframe section far outside the viewport do not advance. Pages should expose atick()hook the harness can pump (every ~50 ms; at 16 ms a loaded desktop timed out and looked like a hang). For workers, hold the load event open with a deliberately slow resource (/__slow?ms=) and run in real time. --dump-domfires before ES modules finish. Benchmarks used the difference method instead: wall clock of a 3300-frame run minus a 300-frame run.- Synthetic pointer ids.
canvas.setPointerCapture(id)throws for syntheticPointerEvents; wrap it in try/catch. - Navigating twice quickly gives "Failed to fetch" from the aborted first load, and navigating mid view-transition logs "AbortError: Transition was skipped". Wait for the page's own ready signal, not a sleep.
- Media elements that are not in the DOM. Flutter's
just_audioon web plays through an<audio>element it never attaches, so a CDP query finds nothing. Verify playback through app state instead (a persisted position that keeps advancing). That route also caught a real bug: a listener overwriting the saved position with 0 during session restore (see just_audio in Flutter, gotchas and patterns). -
Port collisions. A stale
http.serveralready on the port (rooted somewhere else) means every screenshot is a 404 page while the "is it listening" guard happily skips starting yours. Pick a free port, start with--directory. -
The overflow check can lie. Under Chrome mobile emulation
window.innerWidthgrows to the overflowing layout width, soscrollWidth - innerWidthreads 0 on a page that really overflows. Comparedocument.documentElement.scrollWidthto the device width (e.g. 390) instead. (plumb, 2026-10-06) --dump-domalso serializes<script>source. A marker string that appears in both code and rendered output grep-counts about double; grep for something only the rendered DOM has.- rAF-gated state under virtual time reads as "never ran". In Spacebar a working Esc-to-menu
flow looked broken five different ways under
--virtual-time-budget. A small CDP driver (tools/uicheck.mjs: real clock, real key events, screenshot at the end, steps like[["wait",2000],["key","Enter"]]) gave the right answer. - Truncated output filenames overwrite each other. Two URLs mapped to the same shortened screenshot name; the second silently replaced the first and produced a false "campaign mode is broken". Use distinct names per URL.
- Screenshot byte size is a cheap state fingerprint: in Spacebar the menu was about 21 KB, gameplay about 7 KB, the editor about 48 KB. A dead band at the bottom of headless shots appeared in every mode identically (artifact, not bug).
When a test fails, suspect the harness first
- A wall-collision simulation reported NaN and "tunneling" because the harness called a pre-dt API and used a moveable block; neither was a game bug.
- Node heap-delta "leaks" that shrink as iterations grow are JIT warm-up; warm up about 3,000 iterations, then compare growth against N.
- Verify an automated reviewer's key claims by measurement before acting on them (Adversarial review before architecture decisions).
- Keep regression simulations in the repo (e.g.
tools/sims/), not a session scratch directory where they vanish.
Cheap checks without a full harness
- Syntax-check inline JS without a browser: extract the
<script>blocks and runnew (require('vm')).Script(block)in Node; parse errors surface instantly. For module files,node --check file.js. - Module-level smoke page: a temporary
test-smoke.htmlthatimports the app's ES modules directly, stubs state through exported setters, calls a view'srender(), and writesdocument.title = 'RESULT ' + JSON.stringify(checks). Rungoogle-chrome --headless=new --disable-gpu --no-sandbox --virtual-time-budget=8000 --dump-dom URL | grep -o '<title>[^<]*</title>'. Delete it before a deploy that rsyncs the whole directory. - Authenticated pages: seed the session (e.g. a JWT in localStorage) with
Page.addScriptToEvaluateOnNewDocument(puppeteer:evaluateOnNewDocument) before navigating. - Where
puppeteer-coreis available, launch it against the system Chrome (executablePath: '/usr/bin/google-chrome') and usepage.setViewport({width: 390, isMobile: true})for a true mobile layout viewport. Without puppeteer, a throwaway Node script speaking CDP over Node's globalWebSocketat 390x844 that collects console errors and screenshots did the same job for the plumb web app. - Benign stderr noise to ignore:
shared_memory_switch, GPU/GLES/Vulkan/Dawn/tflite and voice lines. Real page errors sayUncaught. - A 200 from curl proves the file was served, not that the page works; render it.
Harness pattern that works
- Serve the repo (
python3 -m http.server --directory ...orphp -Swith a scratch config), load asmoke.htmlorpage.htmlthat iframes the real page, call the page's test hook (window.OD2,window.MEASLY,window.RECOURSE), print one line per check into a<pre>, read it with--dump-dom. ?test=1disables the page's own rAF loop and?seed=Nmakes the RNG deterministic so the harness ticks by hand.- Clear spawned entities between frames in pure-physics tests; respawned traffic colliding with the test car once faked a 370 to 61 speed "bug".
- Test pages must live inside the served root; copy them in, shoot, delete.
- For a real phone pass, a CDP script with a 390x844, 3x touch device, CPU throttled 4x and real touch events catches more than iframes do, but is still not a phone (see When headless tests and a real phone disagree).
Gotchas
- A crashed CDP script leaves its Chrome running on the debug port, and the next run silently attaches to that old browser, old flags and all, so a flag you just added appears to do nothing. Kill the leftover by PID or use a fresh port per run.
- Make one host unreachable with
--host-resolver-rules="MAP storage.example.com 0.0.0.0"to test a fallback path (a blocked CDN or storage host) on a machine where the direct path works; see Upload links for people without an account (getting a full-quality video from a friend). - Offline second launch: to test a cache that should paint without the network, run the app once normally, then again with the same
--user-data-dirand--host-resolver-rules="MAP api.example.com 0.0.0.0". For a single-page app, serve the build with an SPA fallback and prime sign-in from a same-origin page that writes the auth keys intolocalStorage(Perceived load time in a Flutter app and a cold-start disk cache). - Signing in as a real account has side effects. Loading a messaging app as a service account made the app generate and publish an encryption key for it, which then had to be removed from the database. Use a throwaway user, or block the endpoints that register keys or devices.
- Pick a free port for the test server by checking, not by habit; a remembered port may be another project's dev server.
- ffmpeg/ffprobe segfault when handed a pre-signed URL that returns an error body;
curlit to a file first.curl -Ion a GET-presigned URL is a 403 because SigV4 signs the method. - Headless at a stage-sized iframe did not reproduce an Android overflow because Android's monospace fallback font is wider. Believe the phone.
See also
- Touch compatibility mouse events (mousemove before click)
- Fixed page backgrounds on mobile (background-attachment vs position fixed)
- When headless tests and a real phone disagree
- Test harnesses for browser canvas games and simulations
Linked from
- "Anyone with the link" share links (capability URLs)
- 1:1 WebRTC voice calls over polled signaling and TURN
- A production vanilla-JS single-page app (no framework, no build)
- CSS layout gotchas on phones
- Driving a desktop from a headless agent shell (DISPLAY, clipboard, sudo hand-off)
- Fixed page backgrounds on mobile (background-attachment vs position fixed)
- Fixed-timestep game loop for browser games
- just_audio in Flutter, gotchas and patterns
- Offline-first browser tools (module workers, precache lists, no build step)
- Perceived load time in a Flutter app and a cold-start disk cache
- Simulating Chladni figures (sand on a vibrating plate)
- Static trivia and quiz games (daily sets, question banks, fact checking)
- Test harnesses for browser canvas games and simulations
- three.js in a static site (bundling, viewers, snapshots)
- Touch compatibility mouse events (mousemove before click)
- Upload links for people without an account (getting a full-quality video from a friend)
- Web video players: sound, mute, fullscreen and autoplay-next
- When headless tests and a real phone disagree
- Where-to-stream lookups (TMDB watch providers and the Streaming Availability API)
- Zero-build web apps (vanilla JS, localStorage, single file)