Testing games
shoehive/testing drives a game without sockets, a server or real time. A test table runs
your rules exactly as the server does, with the checks that catch mistakes always on: frozen
state, JSON validation and the nondeterminism guard. Tests are fast and reproducible because
randomness is seeded and time is fake (ADR 0006).
The examples use Vitest, but any runner works.
Create a table and play
Section titled “Create a table and play”createTestTable(game, options) seats the players, waits for the table to settle and returns
a TestTable. t.act(seat, name, input) runs an action as the player in that seat.
it('rejects a move out of turn', async () => { const t = await createTestTable(ticTacToe, { players: 2 }); await expect(t.act(1, 'place', { cell: 0 })).rejects.toMatchObject({ code: 'NOT_YOUR_TURN', source: 'game', }); expect(t.state.board[0]).toBeNull();});A rejected action makes act reject with a ShoehiveError. Check code for your own
reject('NOT_YOUR_TURN') codes, and source to tell game rejections from built-in ones
(see error codes). A rejected action changes nothing.
it('X wins on the diagonal and the table ends', async () => { const t = await createTestTable(ticTacToe, { players: 2 }); for (const [seat, cell] of [ [0, 0], [1, 1], [0, 4], [1, 2], [0, 8], ] as const) { await t.act(seat, 'place', { cell }); } expect(t.state.winner).toBe('X'); expect(t.meta.status).toBe('ended'); expect(t.meta.result).toEqual({ winner: 'X' }); await expect(t.act(1, 'place', { cell: 3 })).rejects.toMatchObject({ code: 'TABLE_ENDED' }); await t.verifyReplay();});t.state is the raw committed state, t.meta the table status, phase, turn and result, and
t.rev the revision. End every test with await t.verifyReplay(): it replays the log from
scratch and throws unless the result matches the live table exactly.
Options
Section titled “Options”it('seats players by count or by id, with a seed and a wallet', async () => { const wallet = new MemoryWallet({ startingBalance: 1000, balances: { ada: 30 } }); const t = await createTestTable(blackjack, { players: ['ada', 'bo'], // or a number: p0, p1, ... seed: 'my-seed', // default: 'shoehive-test' options: { minBet: 25 }, // checked against the game's options schema wallet, // default: a MemoryWallet giving everyone 1000 }); expect(t.playerAt(0)).toBe('ada'); expect(await t.wallet.balance('ada')).toBe(30);});| Option | Default | Meaning |
|---|---|---|
players |
the game's seats.min |
a count (p0, p1...) or a list of player ids |
seed |
'shoehive-test' |
the RNG seed: same seed, same deal |
options |
none | table options, checked by the game's options schema |
wallet |
a MemoryWallet giving 1000 each |
the money backend behind ctx.wallet |
startAt |
2026-01-01T00:00:00Z | the fake clock's start time, in epoch milliseconds |
Seat changes
Section titled “Seat changes”t.sit(seat, playerId?, name?), t.stand(seat), t.disconnect(seat) and t.reconnect(seat)
are the same events the server raises. Each waits for the table to settle. Use t.start() for
a game with autoStart: false.
it('sits, disconnects and reconnects players', async () => { const t = await createTestTable(ticTacToe, { players: 1 }); expect(t.meta.status).toBe('waiting');
await t.sit(1); // seat 1 as player p1; the table starts expect(t.meta.status).toBe('active');
await t.disconnect(1); // the seat is kept, but marked offline expect(t.seats[1]?.connected).toBe(false); await t.reconnect(1); expect(t.seats[1]?.connected).toBe(true);
await t.stand(1); // the seat is empty again expect(t.seats[1]?.player).toBeNull();});What a player sees
Section titled “What a player sees”t.viewOf(seat) and t.viewOf('spectator') call your view() for that viewer, so you can
assert that nobody sees a card they should not.
it('hides answers until the reveal, then shows everything', async () => { const { t, correct } = await table(); await t.act(0, 'answer', { choice: correct() }); expect(t.viewOf(0).answers).toEqual({ '0': correct() }); expect(t.viewOf(1).answers).toEqual({}); expect(t.viewOf('spectator').correct).toBeNull(); expect(t.meta.round?.submitted).toEqual([0]);
await t.act(1, 'answer', { choice: (correct() + 1) % 4 }); await t.act(2, 'answer', { choice: correct() }); expect(t.meta.phase).toBe('reveal'); expect(t.viewOf(1).correct).toBe(correct()); expect(Object.keys(t.viewOf(1).answers)).toHaveLength(3);});t.events lists the ephemeral events your game emitted, in order, each with its name,
payload, to and the rev that carried it.
The table runs on a fake clock, so a turn timeout or a round deadline costs nothing to test.
t.advance(ms) moves time forward, fires every timer that falls due in order, and waits
for what they trigger. t.clock.now() is the current fake time, and t.clock.pendingTimers
counts the timers still waiting.
it('scores faster correct answers higher, using the recorded clock', async () => { const { t, correct } = await table(); await t.act(0, 'answer', { choice: correct() }); await t.advance(QUESTION_MS / 2); await t.act(1, 'answer', { choice: correct() }); await t.advance(QUESTION_MS / 2); // seat 2 never answers; the round times out expect(t.state.scores.slice(0, 3)).toEqual([1000, 750, 0]);});Seeds and reproducible deals
Section titled “Seeds and reproducible deals”The same seed always gives the same shuffle, so a test that depends on a deal is stable. To get a particular deal, search for a seed once and then pin it in the test:
it('finds a seed that gives the deal you want to test', async () => { for (let i = 0; ; i++) { const t = await createTestTable(blackjack, { players: 1, seed: `deal-${String(i)}` }); await t.act(0, 'bet', { amount: 100 }); if (t.meta.turn?.seat === 0) { // No natural blackjack with this seed: the player has a turn. await t.act(0, 'stand'); expect(t.meta.phase).toBe('dealer'); break; } }});Do not use Math.random() or Date.now() in game code: use ctx.random and ctx.now().
In tests the nondeterminism guard turns such a call into an error.
t.wallet is the wallet behind ctx.wallet. Read balances from it, or pass your own
MemoryWallet to start players with different funds. t.walletErrors collects deferred
wallet operations that still failed after retries, which points to a bug in the game such as
a reused key. Assert that it is empty at the end of any test that moves money.
it('plays a full hand: turns, timeout auto-stand, dealer play and wallet payouts', async () => { const t = await createTestTable(blackjack, { players: 2, options: {} }); await t.act(0, 'bet', { amount: 100 }); await t.act(1, 'bet', { amount: 100 }); // With the default test seed neither player has a natural, so both get a turn. expect(t.meta.turn?.seat).toBe(0); await t.act(0, 'stand'); expect(t.meta.turn?.seat).toBe(1); await t.advance(TURN_MS); // seat 1 times out and auto-stands expect(t.meta.phase).toBe('dealer'); expect(t.viewOf(0).dealer).toEqual(t.state.dealer); expect(blackjackValue(t.state.dealer).total).toBeGreaterThanOrEqual(17); await t.runtime.idle(); for (const seat of [0, 1]) { const hand = t.state.hands[seat]!; const expected = { blackjack: 250, win: 200, push: 100, lose: 0, bust: 0 }[hand.outcome!]; expect(await t.wallet.balance(`p${String(seat)}`)).toBe(START - 100 + expected); expect(t.state.bankroll[seat]).toBe(START - 100 + expected); } expect(t.walletErrors).toEqual([]); await t.advance(NEXT_HAND_MS); expect(t.meta.phase).toBe('betting'); expect(t.state.handNumber).toBe(2); await t.verifyReplay();});See wallets and real-money safety for the rules a game must follow.
Type tests
Section titled “Type tests”act is typed from your game, so a wrong action name or input is a compile error. Keep a few
of these in your tests, with @ts-expect-error, to prove the types stay strict.
it('checks action names and inputs at compile time', async () => { const t = await createTestTable(ticTacToe, { players: 2 }); // This function is never called: the point is that tsc accepts the three errors below. const misuse = async () => { // @ts-expect-error there is no action called "play" await t.act(0, 'play', { cell: 0 }); // @ts-expect-error cell must be a number await t.act(0, 'place', { cell: 'centre' }); // @ts-expect-error this action needs an input await t.act(0, 'place'); }; expect(misuse).toBeTypeOf('function'); expectTypeOf(t.viewOf(0)).toHaveProperty('board');});Property tests
Section titled “Property tests”Rules that hold for every sequence of commands are best checked with random ones. The
engine's own invariants are tested this way with fast-check in
packages/shoehive/test/properties/invariants.test.ts:
generate commands (actions with wild inputs, seat changes, time jumps), run them against
a test table, and after each one check what must always be true. The core of it:
import fc from 'fast-check';
await fc.assert( fc.asyncProperty(commands, async (cmds) => { const t = await createTestTable(game, { players: 2 }); for (const cmd of cmds) { const before = { state: t.runtime.state, log: t.log.length }; try { await run(t, cmd); } catch (error) { expect(isShoehiveError(error)).toBe(true); // never a crash expect(t.runtime.state).toBe(before.state); // a rejection leaves no trace expect(t.log.length).toBe(before.log); } } await t.verifyReplay(); // and the log always replays to the same state }),);Add your game's own rule, for example "chips are conserved" or "no view shows the deck".
When fast-check finds a failure it shrinks it to a short command list you can paste into
a normal test. It needs fast-check as a dev dependency.
Replay an exported fixture
Section titled “Replay an exported fixture”A bug seen in devtools can become a test. Export the table
as a fixture, save it as JSON, and replay it. replayFixture(game, fixture) checks the game
and its version, replays every entry exactly, compares the state with the exported hash, and
returns a live test table at the last entry.
it('plays on from an exported fixture', async () => { const t = await replayFixture(ticTacToe, fixture as Fixture); expect(t.state.board[4]).toBe('X'); // the table is at the last exported entry await t.act(1, 'place', { cell: 0 }); // and it keeps running await t.verifyReplay();});If your rules changed since the export, replayFixture throws instead of quietly replaying
something different. Bump the game's version and export again, or keep the old fixture as a
record of the old behaviour. A fixture keeps the RNG seed, so treat one from a production
table as a secret.
