Automated Testing for Three.js Games: A Browser in a Node Sandbox
The browser has things Node does not: WebGL, AudioContext, requestAnimationFrame, Canvas. But the game logic itself is plain JavaScript. So the approach is to stub every one of those browser objects, drop them into a Node vm sandbox, and let the game code run unmodified.
Why Playwright is the wrong tool here
The instinct is to reach for Playwright or Puppeteer: open the page, inject a script, assert. But a 3D game’s logic does not live in the DOM — where the BOT is, whether a shot hit, whether damage was computed correctly all live in in-memory objects and arithmetic. The DOM can only tell you the canvas exists.
The second path is to simulate the entire browser environment with stubs. That takes a few things:
- A fake
AudioContextwhere every node method returns an empty object - A fake Canvas 2D context — a Proxy that swallows any property access
- Fake DOM elements —
getElementByIdreturning objects withstyle,classListandtextContent - A fake
requestAnimationFrame— but it must be a queue, not immediate execution - A fake
WebGLRenderer— Three.js will genuinely try to construct one
The critical detail: three must run inside the sandbox too
This one bit us. If you only run game.js in the sandbox and load three.min.js with a normal require, it fails outright — Three.js reads document at load time, and it gets Node’s real (nonexistent) document rather than your stub.
The fix is to run both files in the same sandbox context:
vm.createContext(sandbox);
vm.runInContext(fs.readFileSync('three.min.js', 'utf8'), sandbox);
if (!sandbox.THREE) throw new Error('THREE 未挂载');
// 再把 game.js 也塞进同一个沙箱Three.js ships as UMD and attaches itself to the sandbox’s THREE, so game.js then uses that very same instance.
Three traps you only learn by hitting them
RAF is a shared queue
The game does not only register requestAnimationFrame in the main loop — shockwave effects and blast particle spawns do too. So "advance one frame" in a test cannot call RAF once; it must drain the queue. Otherwise effect callbacks always queue behind the main loop and the frame order is scrambled.
The stub’s innerHTML must feed textContent
In a browser, after el.innerHTML = "x" the el.textContent becomes "x". If your stub stores innerHTML as a string but leaves textContent always empty, every assertion either fails spuriously or passes spuriously.
style must support setProperty
HUDs commonly drive a health bar with a CSS variable (style.setProperty("--v", ...)). A stub style object without that method throws outright.
Fix the random seed, or regressions are not reproducible
Map generation uses rand() to place crate sizes and vegetation. Without a fixed seed in tests, the same code produces a different map every run — I once saw the same build report four stuck-position bugs in one run and pass completely in the next.
The fix is to override Math.random inside the sandbox with a deterministic LCG:
vm.runInContext(`
window.__s = ${SEED};
Math.random = function () {
window.__s = (window.__s * 1664525 + 1013904223) >>> 0;
return window.__s / 4294967296;
};
`, sandbox);There is also a cross-realm trap: the THREE.Vector3 class constructed inside the sandbox cannot be called as a plain function from outside. Wrap it in a factory:
vec3: (x, y, z) => new THREE.Vector3(x, y, z)
Four scripts, one job each
Packing every test into one file turns it into a second game.js. It ended up as four scripts, each with one job:
- _smoke.js — integration smoke test. Loads everything and genuinely drives: start → buy → round → cook fuse → throw → explode in hand → toggle suppressor → shoot → suicide → spectate. 59 assertions, plus a long-run mode that plays 1400 frames and watches the heap.
- _mapcheck.js — map reachability. Replicates the colliders, builds a 1-metre grid, runs BFS from both spawn points, and checks whether every key target (bomb sites, sniper posts, lurk spots, ramp entrances) is reachable.
- _stuckcheck.js — stuck-position diagnosis. The self-extraction push when the player is embedded in a collider, the collision semantics of elevated platforms, whether knockback pushes people into geometry.
- _botcheck.js — BOT behaviour metrics. Per-frame yaw change rate, instantaneous snap-turn count, frame share spent on clearing and on reacting to hits, and monotonicity of burst-length limits.
Together these scripts are 1166 lines — far smaller than the game itself, yet they are what made 14 rounds of iteration viable.
A case where the test was the bug
While writing _botcheck.js a false positive appeared: "BOT turning is not rate-limited", measuring one radian per frame. The game code looked genuinely broken.
The diagnostic was to intercept writes to mesh.rotation.y and print the stack trace:
Object.defineProperty(mesh.rotation, 'y', {
get() { return v; },
set(nv) { console.trace('rotation.y 写入'); v = nv; }
});The trace pointed to a single write site, faceYaw, which already had an angular speed cap. The actual bug was in the test: it keyed frames by p.name, and same-team BOTs can share a name — so consecutive frames were comparing two different BOTs’ headings, producing a phantom jump.
That investigation also surfaced a real game bug: picking names with NAME[random] let same-team BOTs share names, making the kill feed, radar and spectate HUD ambiguous. Switching to a shuffled bag made names unique.
The lesson: a test key must be a unique object identity, never a business field that can repeat. Names and titles duplicate in real systems all the time.