pixi-reels
Reference
Harness

Testing model

Why a full spin runs in Node with no renderer.

Slot mechanics are awkward to test. The interesting behaviour, which symbol lands where, whether a sticky wild survived, whether a cascade refilled the right cells, is tangled up with pixels and with time. The obvious approach, spinning a real canvas in a real browser and waiting for it to stop, is slow, flaky and blind: a screenshot cannot tell you that reel 3 holds a wild at cell 1. And nobody wants to wait four seconds of wall-clock time per test to find out.

pixi-reels was designed so that mechanics, not pixels, are what you test. The pixi-reels/testing subpath hands you a real ReelSet, the same class that ships, running against a fake clock and symbols that draw nothing. No canvas, no DOM, no WebGL. You spin it, land it on a grid of your choosing in a single call, and assert on a JSON snapshot. Every test in the library's own suite runs this way in Node under vitest, and each takes milliseconds. The decision is recorded in ADR 008 (docs/adr/008-deterministic-testing.md); the user-facing walkthrough is the cheats and testing guide.

Your first test

Here is a complete test, and then a walk through each line. It builds a five-reel, three-row set with three symbol ids, lands it on a grid the test chose, and checks the grid, a symbol count and the events that fired.

import { it, expect } from 'vitest';
import { createTestReelSet, expectGrid, captureEvents, countSymbol } from 'pixi-reels/testing';

const cells = [
  ['a', 'a', 'a'], ['b', 'b', 'b'], ['c', 'c', 'c'], ['a', 'b', 'c'], ['c', 'b', 'a'],
];

it('lands the grid it was given and fires the round events', async () => {
  const h = createTestReelSet({ reels: 5, visibleCells: 3, symbolIds: ['a', 'b', 'c'] });
  try {
    const log = captureEvents(h.reelSet, ['spin:start', 'spin:complete']);
    // spinAndLand and setResult take ColumnTarget[]; expectGrid takes string[][].
    const result = await h.spinAndLand(cells.map((visible) => ({ visible })));
    expect(result.wasSkipped).toBe(true);
    expectGrid(h.reelSet, cells);
    expect(countSymbol(h.reelSet, 'a')).toBe(5);
    expect(log.map((e) => e.event)).toEqual(['spin:start', 'spin:complete']);
  } finally {
    h.destroy();
  }
});

Build. createTestReelSet(opts) is the one line that replaces the builder, the ticker and the symbol registration. It returns a handle, h, that holds the set (h.reelSet), the fake clock (h.ticker) and the two shortcuts you will use most. The options are the same vocabulary as the builder, with defaults chosen for tests; the full list is in the table further down. The cells array is written reel by reel: the first inner array is reel 0 top to bottom, and so on.

Listen. captureEvents is a recorder. Give it the set and the event names you care about, and it returns an array that fills up in order as they fire. You set it up before you act and read it after, which is why it comes first.

Act. h.spinAndLand(grid) does what a whole round does in production: it starts the spin, hands in the result, and then slams every reel onto it immediately. Note the map: spinAndLand and setResult take a ColumnTarget[], an object per reel with a visible array (and optional buffer cells), while expectGrid takes a plain string[][]. The returned result reports wasSkipped: true, because a slam is, to the engine, a skip.

Assert. expectGrid compares the visible board with your cells and, if they differ, throws a message that lists every mismatched reel and cell and ends with an ASCII drawing of the board, so you can see the failure without a debugger. countSymbol counts one id across the visible grid. The captured log should hold exactly the two events, in order.

Destroy. h.destroy() in a finally tears down the set and then the ticker. Do not skip this: the engine registers ticker callbacks and the fake ticker counts them, so a leak shows up as a non-zero listenerCount after destroy().

That is the shape every mechanic test in packages/pixi-reels/tests/integration/mechanics.test.ts follows: build, act through the public API, assert on the snapshot, destroy in finally. One variation covers most of the rest. A test that needs time to pass, a watchdog, a nudge tween with a synchronous gsap shim, a pin overlay mid-spin, calls h.advance(ms) between the act and the assertion instead of spinAndLand. advance moves the fake clock forward in 16 ms frames, so the engine sees exactly the frames you give it and nothing else.

The data flow

Figure 1 is the test above as a picture, top to bottom. Your test file imports three things from the testing subpath; build() produces a real reel set with every subsystem intact; spinAndLand drives it; and your assertions read the snapshot. Notice that the whole middle band is the same classes production runs. Nothing below the testing module is a mock.

my-spin.test.tsvitest, node environmentimportpixi-reels/testinga subpath export, never in the main bundleFakeTickertick(ms) by handHeadlessSymbolpaints nothingcreateTestReelSet(opts)a builder wired to bothbuild()a real ReelSetthe same classes production runsSpinControllerphases and stepson the FakeTickerReel[]ReelMotion, ReelAxisheadless cellsEventEmittertyped eventscaptureEvents hereFrameBuilderreal pipelinerandom fillspinAndLand(grid)spin() + setResult(grid) + slamStop()assertionsexpectGrid, captureEvents, countSymboldebugSnapshot, debugGrid, getFrames
A test imports three primitives, gets a real ReelSet back, lands it synchronously, and asserts on JSON. Nothing below the testing module is a mock. spinAndLand() lands in the same tick; its promise resolves on a microtask with wasSkipped: true.
the one shortcutspinAndLand
real engine objectsnot mocked
testing moduleFakeTicker, HeadlessSymbol, helpers

What is swapped, what is real

Figure 2 draws the line. On the left are the only two substitutions. On the right is everything that is not substituted, and the list is longer than it looks: the axis and curve maths, the symbol factory and its pool, the speed manager, the masks, pins, cascade and expand all run their shipping code in a test.

swapped2 thingsFakeTickerstands in for PIXI.Tickerbuilder.ticker(ticker)HeadlessSymbolstands in for Sprite, Spine,AnimatedSprite and Cardrealeverything elseReelSetBuilderReelMotionReelSetFrameBuilderSpinControllerEventEmitterphases + stepsReelViewport
Exactly two things are replaced: the ticker, because wall-clock time is the enemy of a deterministic test, and the symbol art, because Node has no renderer. Everything else is the shipping class, including ReelAxis, ReelCurve, SymbolFactory and its pool, SpeedManager, the masks, pins, cascade and expand.

The fake ticker stands in for PIXI.Ticker. It can be that small because the engine never touches a ticker directly: every subscription goes through a wrapper called TickerRef (ADR 004), which only ever calls add and remove and reads deltaMS. So the fake needs those, the handful of fields that make it look like a ticker to TypeScript, and a way to move time by hand. That last part is tick() and tickFor(), and it is the whole reason the harness is deterministic: no requestAnimationFrame, no wall clock, only the frames you ask for. The table lists what it implements.

FakeTickerBehaviour
deltaMS, deltaTime, elapsedMS, lastTimeThe fields the engine reads. deltaMS starts at 16; tick() sets deltaMS, deltaTime = deltaMs / (1000 / 60), and adds to elapsedMS and lastTime.
speed, started, FPS (60), minFPS (10), maxFPS (0)Present so the duck type matches; nothing in the engine reads them.
add(fn), addOnce(fn), remove(fn)The surface TickerRef uses. addOnce wraps and removes itself before calling.
start(), stop(), destroy()Flip started; destroy() also empties the callback list.
tick(deltaMs = 16)Advance one frame: set the deltas, then call a snapshot of the callbacks, so a callback that removes itself does not skip its neighbour.
tickFor(totalMs, stepMs = 16)Loop tick(min(stepMs, remaining)) until totalMs is spent.
listenerCountHow many callbacks are registered. Handy for leak tests: it must be 0 after destroy().

The headless symbol is not a mock, and the distinction matters. It is a real subclass of ReelSymbol, the same base class the sprite, animated, Spine and card symbols extend. It creates an empty Container for its view so the reel's child-tree code has something to attach, and it implements the lifecycle hooks as no-ops: onActivate and onDeactivate do nothing, playWin resolves immediately, stopAnimation is empty, and resize(width, height) stores the two numbers so width and height read back. A Reel cannot tell it from a SpriteSymbol. That means a test exercises the real pool lifecycle, acquire, activate, resize, deactivate, release, and if a change broke that lifecycle, the testing module would be the first thing to fail.

createTestReelSet

The one-liner lives in testing/testHarness.ts. It builds a ReelSetBuilder with a fresh FakeTicker, registers every id you list as a HeadlessSymbol, forwards the options below, and returns a TestReelSetHandle: { reelSet, ticker, advance(ms, stepMs = 16), spinAndLand(grid), destroy() }. advance is ticker.tickFor; destroy destroys the set and then the ticker. The options mirror the builder, so anything you can build in production you can build in a test.

OptionDefaultMeaning
reels5reel count
visibleCells3a number, or a per-reel array for a static pyramid; exclusive with multiways
multiwaysnone{ minCells, maxCells, reelExtent }; the set starts at maxCells
symbolIds['a', 'b', 'c']every id is registered as a HeadlessSymbol
weights, symbolDatanoneforwarded to the builder; symbolData is how tests declare big symbols
symbolSize{ width: 120, height: 100 }non-square on purpose, see below
symbolGapbuilder default (0, 0){ x, y }
orientation, direction, directionPerReelvertical, forwardthe axis options, same as the builder
curve, curvePerReel, curveFocusflatdrum curvature, same as the builder
tumblenonepass {} for the cascade defaults; without it the set spins strips
bufferSymbolsbuilder default (1)a number or { start, end }
phasesnonethe same hook as ReelSetBuilder.phases(factory)
skipModebuilder default (slam)what a bare skip() does
initialFramerandomColumnTarget[], same as ReelSetBuilder.initialFrame
gsapthe library defaulta per-set gsap instance, for example a synchronous shim

The helpers

These are the five helpers the first test used, plus the frame recorder, with the exact rules each one follows.

HelperBehaviour
spinAndLand(reelSet, grid: ColumnTarget[])spin(), then setResult(grid), then slamStop(). slamStop() force-completes every active phase including its GSAP timelines, places the target symbols directly and fires the usual landing events, so the promise resolves on a microtask with wasSkipped: true. It is the same internal slam path a player's skip uses, minus the speed boost. It takes ColumnTarget[] only; the old string[][] form is gone and setResult throws on it.
captureEvents(reelSet, names)Returns an array of { event, args } that fills up in order as the named events fire. Read it after the act.
expectGrid(reelSet, string[][])Compares debugSnapshot(reelSet).grid with what you expect and throws a readable diff that lists every mismatched reel and cell and ends with the ASCII debugGrid().
countSymbol(reelSet, id)Counts visible occurrences of one id, for scatter-style assertions.
startRecording, stopRecording, getFrames, clearFramesFrom the main barrel (debug/debug.ts), not the testing subpath. startRecording(reelSet, tag, { maxFrames }) captures a debugSnapshot on spin:start, spin:reelLanded, spin:allLanded and spin:complete; getFrames(tag?) returns a copy. The buffer is process-wide and capped at 1000 frames. See the debug page.

The deterministic surface

A test is only useful if it fails for the same reason every time. Figure 3 shows the four knobs that make a run repeatable. The seeded random generator fixes the filler symbols between results. The fake ticker fixes time. The non-square default cell makes a whole class of bug impossible to miss. And the cheats package gives you forced outcomes with a name.

builder.rng(fn)seeded PRNG for the random fillsame seed, same strips and wrapsFakeTicker.tick(16)tickFor(ms, 16), advance(ms)no requestAnimationFrame120 x 100 cellnon-square on purposeaxis mix-ups fail loudly@pixi-reels/cheatsCheatEngine, SeededRngevaluateWays, countWays
Four knobs that make a run repeatable. The non-square default cell is the cheapest of them (ADR 018, section 10.2): with a square cell, swapping width for height passes every assertion.

The cell size deserves a sentence. The default test cell is 120 wide by 100 high, and that is deliberate: the library supports horizontal and reversed reels, and the most likely bug in that code is using width where height was meant. With a square cell such a bug passes every assertion. With a non-square one it fails loudly and immediately. ReelSetBuilder.rng(fn) takes any () => number and hands it to the random symbol provider, so the strips between results are reproducible from a seed.

The cheats package is deliberately outside the library (ADR 009), because forcing an outcome is something a game's demo mode and its tests need but a shipped game must never contain. Its built-in cheats are forceGrid, forceLine, forceScatters, forceNearMiss, forceCell, forceAnticipation, holdAndWinProgress and cascadingStages. A CheatEngine tries its registered cheats in order, each a CheatDefinition { id, label, description?, enabled, cheat }, and the first one to return a non-null CheatSpinResult { symbols, anticipationReels, meta? } wins; if none does, it produces a seeded random grid. Held cells are applied on top of every result. Its SeededRng is Mulberry32 with a default seed of 0xdeadbeef, and the engine seeds it with 1. evaluateWays(grid, { wilds?, exclude?, minReels = 3, pays? }) and countWays(cellsPerReel) live there too, because the core library never evaluates wins (ADR 007). The docs site and the library's own integration tests both import it; a published game never does.

Three suites around the harness

The library tests itself at three levels, and the split is a useful template for a game. Mechanics go through the harness. The motion maths is checked as properties, below the harness, because it must hold for every input. And a small browser suite covers what only a browser can tell you.

tests/integration

Mechanic tests built on createTestReelSet: pins, movePin, expand, cascade, big symbols, columns, rows, hold reels, the spin watchdog, spotlight, teardown, and the cheats. mechanics.test.ts is the template every new mechanic test copies.

tests/contract

The fourteen laws of ADR 018 as fast-check properties, run against the shipping ReelMotion in all four orientation x direction combinations, plus the isomorphism and mirror laws one level up at the ReelSet, and frame-by-frame golden position traces as inline snapshots. Deliberately driven from ReelMotion directly, not a full spin, because GSAP tweens are wall-clock driven and would make the baseline flap.

tests/e2e

orientation-matrix.spec.ts runs the four travel combinations in a real browser with Playwright: WebGL, a real requestAnimationFrame, GSAP on the Pixi ticker, the full async lifecycle. It asserts engine state through __PIXI_REELS_DEBUG, not screenshots, because WebGL baselines are GPU- and platform-dependent. cascade-rounds and recipes-mount sit beside it.

Why this composition is testable

None of this would work if the engine assumed a renderer anywhere but at the edges. It does not. The only code that knows about textures, Spine or card faces is the concrete ReelSymbol subclasses. All the control flow, the controller, the phases and the events, is plain JavaScript that reads time from a ticker and drives tweens through an injected gsap. Swap the symbols for HeadlessSymbol and the ticker for FakeTicker and the whole thing runs in Node.

The module ships as the ./testing subpath (it moved out of the main barrel in 1.0.0), so a production bundle never sees it, and createTestReelSet is public API: you test your own mechanics with the same harness the library uses on itself.

Where this lives

packages/pixi-reels/src/testing/
  • FakeTicker.ts, HeadlessSymbol.ts
  • testHarness.ts createTestReelSet, spinAndLand, captureEvents, expectGrid, countSymbol
  • index.ts the pixi-reels/testing barrel, debug/debug.ts the recorder
suites and decisions
  • packages/pixi-reels/tests/ unit, integration, contract, tests/e2e/ Playwright
  • packages/cheats/src/ cheats.ts, seededRng.ts, ways.ts
  • docs/adr/008-deterministic-testing.md, 009-cheats-live-outside-lib.md, 018-motion-contract.md