Headless tests
A game’s tests run in Node. There, the devtools store and the harness step the world, draw nothing and load no asset.
Sample
Section titled “Sample”In Node, the store comes from @spawnite/engine/devtools and the harness from @spawnite/engine/core, so nothing draws and no asset loads. A game with its own systems passes its plugins to createHeadlessGame as plugins, the same list it gives Game.
The following file makes a scene of three coins as a spawn function, steps it five seconds, and reads the dump. step(5) is five seconds of game time. The step fixture of a test, which Pin it in a test describes, counts fixed steps instead, so its step(5) is five steps, 1/12 s:
import { createHeadlessGame, PickupTrait, requireAuthority, spawn,} from "@spawnite/engine/core";import type { WritableWorld } from "@spawnite/engine/testing";import { attachDevtools, useDevtools } from "@spawnite/engine/devtools";
/** Three coins in a row ahead of the spawn: the scene, as a function that * spawns into the world. */export function spawnCoins(world: WritableWorld) { for (const x of [-2, 0, 2]) spawn(requireAuthority(world), { position: [x, 0.5, -4], traits: [PickupTrait({ reward: 1 })], });}
/** Steps the scene five seconds with nothing drawn, and returns its dump * and its world, which the caller destroys once done. */export async function stepCoins() { const game = await createHeadlessGame({ scene: spawnCoins }); const detach = attachDevtools(game); const { step, dump } = useDevtools.getState();
step(5); const { entities, hash } = dump(); detach(); return { entities, hash, world: game.world };}A scene’s own component mounts in Node too, through the engine’s headless mount, on the room’s own renderer, which holds nothing. It renders the scene’s logic, and the traits the logic fills are what the steps run on.
A headless mount renders no entity’s view and no <Views>, as a room does, and the engine’s own views, such as the camera, Hud and Panel, skip themselves wherever they stand. A game’s own component that draws, loads a file or reaches the page goes in a view, as Logic and views says. A drawn element or a React Three Fiber hook outside a view fails the mount with an error that names the component, such as Rock renders <mesh> outside a view, and a room draws nothing. One that loads a file another way, or reaches for window, fails with Rock failed headless: and the same fix. Logic that must differ headless reads useHeadless().
useQualityStore() works headless too: each mount builds its own stores, which start empty and keep nothing once it ends. A headless mount saves nothing; spawnite simulate --save <file> starts the world from a save file. The mount makes a world from the core alone unless it is handed one, so a scene that places a character or a behaviour mounts on a world made from the game export. A scene that calls useLevels() mounts on the game’s levels, which the world made from it holds.
The components render between the calls that step the world, not between the steps, so a modal that opens on a step, a match screen for one, holds none of them up: read the match’s state off the dump. The mount returns once every render and effect it started has run, a first load the scene waits on included. In React’s development build it waits under React’s act; in its production build, which has no act, it waits until React’s scheduler is idle and no update waits to commit. A room run with NODE_ENV=production mounts a scene this way.
After the mount, the scene renders between the world’s steps on its own, as a room’s loop does, outside any act. A test that reads what the scene rendered after a step calls await settleHeadlessScene(mounted, () => stepWorld(world)) from the testing entry. It runs the step, then waits until every render and effect the step started has run. With no step it waits for what is pending, and a step that returns a promise, such as a view renderer’s frames beside the scene, is awaited first. The settle runs under act with React’s act flag on for its own call. A test that steps the mounted scene without it, as Juice Island’s test/island.ts does, turns the flag off while the scene is mounted; with the flag on, React warns on every step’s render.
// Excerpt of src/dump.tsimport { createGameWorld, mountHeadlessScene } from "@spawnite/engine";import { attachDevtools, useDevtools } from "@spawnite/engine/devtools";import { game } from "./game";import { Run } from "./scenes/Run";
// On the game's own plugins: a world from coreGame runs the core alone.const mounted = await mountHeadlessScene(Run, createGameWorld(game));const detach = attachDevtools(mounted);useDevtools.getState().step(5);const { entities, hash } = useDevtools.getState().dump();detach();await mounted.unmount();mounted.world.destroy();The cli’s spawnite simulate --scene <name> and the MCP’s simulate tool mount the component src/scenes/<Name>.tsx exports under that name this way, loading it and the engine through the game’s own Vite. They step the world on the game the scene’s file re-exports, else on the one src/game.ts exports, else on the core alone, with the game’s levels as Game plays them. They step it for seconds of game time or until an expression holds, with keys held through the game’s own key table, as its page reads them. Then they print this dump with its hash, the plugins the world was made from, each with its description, and the step’s systems, one line per phase.
Send a command in a run
Section titled “Send a command in a run”--command, or the MCP’s commands, sends one of the game’s commands from the player’s page during the run, through the same send a player’s client uses. Give its name alone, such as --command guard.parry, to send it at the start with no fields. Give a JSON object to set its payload, the second it goes at and the entity it acts through:
spawnite simulate --scene arena --seconds 0.3 \ --command '{"name":"abilities.cast","atSeconds":0.1,"payload":{"ability":"frost-nova","target":null}}'The payload is in the shape the wire carries, an entity as its dump key, as spawnite play commands lists each command’s fields. Without entity, the command acts through the entity the player’s keys steer, such as the player’s character. Give --command again to send more. Each goes after the steps its second rounds to, so they go in time order, and two due on the same step go in the order given.
A line above the dump names the step each command went on and its result, such as Sent abilities.cast on step 6: abilities.cast was accepted by the system abilities.cast. The game’s own refusal, such as a cooldown, is a result like any other. --json carries each command’s result under sends, beside the dump’s own commands. With --until, a command due after the condition held is not sent, and its line says so. The run stops with an error, before it steps or as the command goes, for a name the game declares no command under, a field the command does not declare, a payload out of its shape, naming the field, and a second at or past the run’s end.
What a test imports
Section titled “What a test imports”A game’s tests import the engine the way its source does: from @spawnite/engine, @spawnite/engine/core and the plugin entries, such as @spawnite/engine/characters, as the game’s lint holds.
The testing entry, @spawnite/engine/testing, holds what a test needs beyond them. Pin it in a test lists test and its fixtures, createTestWorld and scene among them, and addPlayer. The entry also holds the following:
WritableWorldandWritableEntity: the world and the entities a fixture writes directly, andreadWritableWorld(world)for the world a mounted<Game>handsuseWorld.openViewWriter(world): a view’s writer outside React, open until itsclose().readHeldInputs(world)andreadHeldInput(world, handle): what a page’s keys and touch controls hold, as a frame reads it before a step.readQueuedCommands(world, command): the commands a page queued for its room, oldest first, of one command where one is given. Each has its name,plugin.key, and its payload as the wire carries it, where an entity field holds the entity’s dump key. Nothing sends them in a test until a joined page’ssend(), so until then the list only grows.isSaveRequested(world): whether the game asked its room for a checkpoint.setUnixSeconds(world, seconds): stands the world’s Unix clock, whichreadUnixSecondsreads, atsecondsfrom the tick it steps next. A world a test or a headless game makes starts at 2000-01-01T00:00:00Z, andcreateHeadlessGametakesunixSecondsto start elsewhere. Time while the game is closed uses it to close a game for a day.setHeldWorld(world, held): holds a world in a test’s world, as a room does once the platform names it, soreadHeldWorldanduseHeldWorldread it. Each fieldheldleaves out reads as a player’s unlisted world, sosetHeldWorld(world, { isCreatorOwned: true })holds a public one. Null holds none. A room names the world it holds and streams it to each joined page, sosetHeldWorldthrows on a room’s world and on a page’s.setWorldStanding(world, player, standing): gives a player a standing in that world, such asWorldStanding.Visitor, as a room does when the player joins. A test of a rule for visitors or members sets it.setWorldRole(world, role), withWorldRole.RoomorWorldRole.Page, andjoinPage(room, page, options): a room’s world and a page joined to it, in one test, as the next section says.testScenesInRoom(scenes, options): one case per scene file, each scene mounted and stepped as a development room runs it, as Every scene in a room says.
A game’s tests take its plugins through the plugins fixture, the list every world of a case is made from. One line at the top of a test file sets it, const it = test.extend("plugins", () => game.plugins), with game from the game’s src/game.ts. A case that needs another list makes its world with createTestWorld({ plugins }). The sample in A room and a page in one test sets the fixture the same way.
WorldProvider, which hands a world to a component rendered alone, such as a HUD’s button, is on @spawnite/engine beside useWorld. A HUD’s test renders in the DOM, so its file starts with // @vitest-environment jsdom where the game’s tests run in Node.
A Hud and a Modal, and so a kit screen built on them such as MatchScreen, throw under WorldProvider alone, because they need the screen layer and the stores that only <Game> mounts. A test of one renders the whole game, as A whole game in jsdom says. A component built from Hud, Panel and Modal alone has a cheaper route, as A HUD alone says. A button or a readout outside a Hud renders under WorldProvider, as the button in the next section’s sample does.
A HUD alone
Section titled “A HUD alone”A test of one HUD component built from Hud, Panel and Modal, such as a score readout or a shop sheet, needs none of the game: it renders the component and reads the DOM. The three throw outside <Game>, so the test replaces them with fakeHud() from @spawnite/testing/hud. It draws a Hud and a Panel as their children alone and drops a Panel’s own props, such as its slot.
The fake Modal keeps the engine’s stack: only the last opened of the open modals draws, so a card opened from inside a menu hides the menu in the test as it does in the game. It draws its children under the pane test id and its actions under actions.
The vi.mock call stays in each test file, because Vitest hoists it only there. The example’s clock test opens this way:
vi.mock("@spawnite/engine", async (importOriginal) => ({ ...(await importOriginal<typeof import("@spawnite/engine")>()), ...(await import("@spawnite/testing/hud")).fakeHud(),}));A kit screen such as MatchScreen takes its Modal from @spawnite/engine, so the same mock covers it. A test that asserts where a Panel lands, such as its slot or its order, keeps a stand-in of its own that writes those props to the DOM.
A room and a page in one test
Section titled “A room and a page in one test”A test plays its game in a room without a server. One world takes the room’s role and another the page’s, each before its scene mounts. Mounting the scene on the page is optional: the stream brings the room’s entities either way, and a scene mounted on both is matched by its entities’ places in the scene.
joinPage(room, page, { player }) welcomes the page as the room’s own welcome does, and the page holds the room’s world once it returns. player is the player entity addPlayer(room, { name }) returned; the page joins as that player and predicts what the player controls. Left out, the page joins as a spectator, which sends no command: a HUD’s test joins as a player. One player joins on one page, as a room hands a player’s seat to that player’s newest page. The welcome names the room world’s tick rate, and sendsPerSecond the room’s sends a second, which divide it: a send each tick unless the game’s defineRoom names fewer. Every page of one room joins at one rate.
The join answers the page’s world, its input, its player, and four calls:
receive()hands the page what the room’s next send would: what changed since the last send, the player’s own traits, the events since, and the results of the player’s commands the room has settled.step(steps, input)steps the page as a page in a room steps, readinginputor the answer’s own. The page’s moves never reach the room.send()hands the room the commands the page queued, as the player’s socket would, for the room’s next step to answer. A predicted command leaves the page once a page step has stamped it with its tick, so the test steps the page, sends, and steps the room untilreadWorldTick(room)reachesreadWorldTick(page), since a page runs ahead of its room.readWorldTickis on@spawnite/engine/core.findPageEntity(entity)answers the page’s copy of a room’s entity, or null until the stream brings it.
dropPlayer(room, player), on the testing entry, closes the player’s page’s socket, as a room’s close does. Until the player rejoins, send() and receive() throw, a predicted command the player’s page stamps is refused late, and the page’s outbox keeps the player’s other commands. rejoinPlayer(room, player), then joinPage(room, page, { player }) again, rejoins the same page under its page id. The player’s welcome brings the results the room settled in the player’s hold, send() sends again each command with no result, and the room runs each one once. The handle the first join returned throws from then on.
A page holds the results of the player’s commands as a HUD reads them: readCommandResults(page, handle), on @spawnite/engine, lists the last results of one command, newest last, each with its status, so a test checks a command was answered once.
So one test runs a button, the room and every page: the button sends its command, send() carries it, a room step answers it, and receive() brings the result to each page. Where a scene is mounted on the page, its components answer the stream in React effects, so the test wraps joinPage and each receive() in await act(async () => { ... }), as a HUD’s test wraps a click.
The join and each receive() compare the page’s copy of every streamed entity with the room’s send, and throw, naming the entity and the trait, where they differ, such as after a page wrote a trait the room streams. Unity’s Netcode test worlds pair a server world and client worlds in one process the same way. Commands says how a HUD sends one with sendCommand.
// @vitest-environment nodeimport { createElement } from "react";import { expect } from "vitest";import { defineTrait, Entity, readTrait } from "@spawnite/engine";import { joinPage, setWorldRole, test, WorldRole,} from "@spawnite/engine/testing";
// A scene in a room and on a page joined to it, in one process: the// sample the Headless tests page shows whole.
const LampTrait = defineTrait("roomAndPageLamp", { lit: false });
function Street() { return createElement(Entity, { position: [0, 0, -4], traits: [LampTrait()], });}
test("streams the room's lamp to a page that joined it", async ({ createTestWorld, scene,}) => { const room = createTestWorld(); const page = createTestWorld(); // Each role before its scene mounts. setWorldRole(room.world, WorldRole.Room); setWorldRole(page.world, WorldRole.Page); await scene(Street, room.world); await scene(Street, page.world);
// The page holds the room's street once the join returns. const joined = joinPage(room.world, page.world); const lamp = room.world.queryFirst(LampTrait); if (!lamp) throw new Error("The room's street has no lamp."); const copy = joined.findPageEntity(lamp); if (!copy) throw new Error("The page holds no copy of the room's lamp.");
lamp.set(LampTrait, { lit: true }); room.step(); joined.receive();
expect(readTrait(copy, LampTrait)).toEqual({ lit: true });});The following file runs a command’s whole route: Ada’s Cheer button on her page, send(), a room step, and receive() on Bea’s page. The button renders under WorldProvider on Ada’s page world, and the test clicks it as a player would. The second case drops Ada before the room answers her cheer, rejoins her page, and checks the cheer ran once:
// @vitest-environment jsdomimport { fireEvent, render, screen } from "@testing-library/react";import { expect } from "vitest";import { Button, CommandStatus, defineCommand, definePlugin, defineSystem, defineTrait, Phase, readCommandResults, readCommands, readTrait, sendCommand, setTrait, useWorld, WorldProvider, type AuthoritativeStep,} from "@spawnite/engine";import { addPlayer, dropPlayer, joinPage, rejoinPlayer, setWorldRole, test, WorldRole,} from "@spawnite/engine/testing";
// A button on one player's page sends the room a command, a room step// answers it, and a second player's page hears the result; and a page// that drops and rejoins sends its command again, which runs once: the// sample the Headless tests page shows whole.
const CheersTrait = defineTrait("cheerButtonCheers", { count: 0 });
/** Counts each cheer since the last step on the room's crowd. */function countCheers(step: AuthoritativeStep) { const crowd = step.world.queryFirst(CheersTrait); for (const command of readCommands(step, cheers.commands.cheer)) { if (crowd) setTrait(step, crowd, CheersTrait, { count: (readTrait(crowd, CheersTrait)?.count ?? 0) + 1, }); command.accept(); }}
const cheers = definePlugin(() => ({ name: "cheers", commands: { cheer: defineCommand({}) }, systems: [ defineSystem({ name: "countCheers", phase: Phase.Rules, answers: ["cheer"], run: countCheers, }), ],}));
/** The Cheer button on a player's HUD. */function CheerButton() { const world = useWorld(); return ( <Button onPress={() => void sendCommand(world, cheers.commands.cheer, {})} > Cheer </Button> );}
// The plugins every world of these cases is made from, as a game's tests// take the game's own.const it = test.extend("plugins", () => [cheers()]);
it("counts Ada's cheer on Bea's page", ({ createTestWorld }) => { const room = createTestWorld(); const ada = createTestWorld(); const bea = createTestWorld(); // Each role before anything joins. setWorldRole(room.world, WorldRole.Room); setWorldRole(ada.world, WorldRole.Page); setWorldRole(bea.world, WorldRole.Page); const crowd = room.world.spawn(CheersTrait()); const adaPage = joinPage(room.world, ada.world, { player: addPlayer(room.world, { name: "Ada" }), }); const beaPage = joinPage(room.world, bea.world, { player: addPlayer(room.world, { name: "Bea" }), });
render( <WorldProvider world={ada.world}> <CheerButton /> </WorldProvider>, ); fireEvent.click(screen.getByRole("button", { name: "Cheer" })); // Her page's socket carries the command, the room's next step // answers it, and its next send reaches Bea. adaPage.send(); room.step(); beaPage.receive();
const seen = beaPage.findPageEntity(crowd); if (!seen) throw new Error("Bea's page holds no copy of the crowd."); expect(readTrait(seen, CheersTrait)).toEqual({ count: 1 });});
it("counts Ada's cheer once when she drops before the room answers it and rejoins", ({ createTestWorld,}) => { const room = createTestWorld(); const ada = createTestWorld(); setWorldRole(room.world, WorldRole.Room); setWorldRole(ada.world, WorldRole.Page); const crowd = room.world.spawn(CheersTrait()); const player = addPlayer(room.world, { name: "Ada" }); const adaPage = joinPage(room.world, ada.world, { player });
render( <WorldProvider world={ada.world}> <CheerButton /> </WorldProvider>, ); fireEvent.click(screen.getByRole("button", { name: "Cheer" })); adaPage.send(); // Her socket closes before the room's next step, and she comes back. dropPlayer(room.world, player); rejoinPlayer(room.world, player); const rejoined = joinPage(room.world, ada.world, { player }); // Her page sends the cheer again, which the room took already. rejoined.send(); room.step(); rejoined.receive();
expect(readTrait(crowd, CheersTrait)).toEqual({ count: 1 }); expect(readCommandResults(ada.world, cheers.commands.cheer)).toEqual([ expect.objectContaining({ status: CommandStatus.Accepted }), ]);});Every scene in a room
Section titled “Every scene in a room”A room refuses a drawn element outside a view. testScenesInRoom finds one in a test, before a room runs the scene.
The call registers one case per scene file. Each case does the following:
- Makes a development room’s world from the
gamethe file exports, or from the core alone where it exports none, as the room reads the file. - Mounts the component the file exports under the file’s name.
- Joins
players, 1 by default, all before the first step, so what a player’s join shows, such as the player’s character, mounts too. The count is not held to the scene’sroomcap. - Steps
secondsof game time, 1 by default, and renders between the steps as a room does.secondsis a whole number of the game’s ticks, 1/30 s each at a room game’s default rate and 1/60 s in a game played alone, and 0 mounts the scene alone. A restart,reloadScene, mounts the scene again, as it does in a room.
A drawn element outside a view fails the case with an error that names its component, whether it shows at the mount, during the steps, at a join or on a restart. A file with no component under its own name fails with the export to write. Every game with a room keeps the test in test/scenes/room.test.ts, and a game created from its template gets it:
// @vitest-environment nodeimport { testScenesInRoom } from "@spawnite/engine/testing";
// Every scene, mounted and stepped as a development room runs it: a drawn// element outside a view fails, naming its component.testScenesInRoom(import.meta.glob("../../src/scenes/*.tsx", { eager: true }));Vite reads import.meta.glob in the file that calls it, so the game hands its scene files in, and a scene that spawnite add scene writes joins the test with no edit. A glob held in a variable first names its type, import.meta.glob<Record<string, unknown>>(...), as the example template’s test/scenes/room.test.tsx does. To leave a file out, add a negative pattern, such as ["../../src/scenes/*.tsx", "!**/Sketch.tsx"].
The test also catches a module that crashes the room on start, such as an import loop that reads a value before its file has run. The room loads its scene’s file first and the rest of the game through it. The test loads the game in that order when both of the following hold:
- The glob matches the room’s scene file alone, as
import.meta.glob("../../src/scenes/Base.tsx", { eager: true }). Vite loads an eager glob’s files in alphabetical order, ahead of the file’s other imports, so a glob of every scene loads the first scene by name first. - The test file starts on fresh modules, as each file does by default. A project with
isolate: falselists the file among the files it isolates, as Holdfast’s Vite config does.
A game that also mounts its other scenes keeps them in a second file, as the example template’s test/scenes/roomStart.test.ts and test/scenes/room.test.tsx do.
The options apply to every file of one call. A scene that needs a longer run, such as one whose boss arrives 30 seconds in, gets a call of its own on its own file, with the others’ glob leaving it out. Holdfast’s scene runs 10 s of game time with four players in about 1.2 s, as measured on a desktop. A run past vitest’s 5 s case limit raises the limit for its file with vi.setConfig({ testTimeout: 60_000 }) from vitest. Each case is named for its scene, such as mounts and steps the Siege scene in a development room, so vitest -t Siege runs that one.
The file runs in Node, as a room does, so it starts with // @vitest-environment node, and the call refuses a page’s window. The test does not check what a room also reads from a scene’s file, such as its room settings, its timeline or its bot: spawnite play does. Unity’s [TestCaseSource] and Godot GUT’s use_parameters make one case per scene the same way, from a list the project gives.
A whole game in jsdom
Section titled “A whole game in jsdom”A test that renders a game’s whole app, Game and its DOM together, runs in jsdom, which has no WebGL. With GAME_ENGINE_VIEWS=off in the environment, the engine leaves out the views that load a model or draw the world. They are a Landscape’s ground, scatter, props, navmesh and light, a Player’s body, footsteps and marker, an Entity’s model and an InstancedModel. The screen, every Hud and Panel, the game’s own DOM and every trait still mount, so the test can find a button and read the wallet. The test still mocks @react-three/fiber and @react-three/drei with the fakes @spawnite/testing/fiber exports, as the example’s test/app.test.tsx does:
import { vi } from "vitest";
vi.mock("@react-three/fiber", async () => (await import("@spawnite/testing/fiber")).fakeFiber(),);vi.mock("@react-three/drei", async (importOriginal) => (await import("@spawnite/testing/fiber")).fakeDrei(importOriginal),);fakeFiber() draws the canvas as a div with data-testid="canvas" that holds its children, with the camera prop as data-camera. Its useThree reads a detached canvas, a 1280 by 720 size, fiber’s default camera’s near, far and position, and an always-running loop. fakeFiber({ state }) puts what state() returns behind useThree’s get, read at each call, so a case can swap the renderer. fakeDrei(importOriginal, overrides) keeps drei whole, draws no CameraControls or GradientTexture, and replaces any export overrides names, such as Html. fakeLoader(importOriginal, () => model) keeps the real fiber and hands every useLoader call the loaded value, for a test that draws with the real renderer. The vi.mock call stays in each test file, because Vitest hoists it only there.
The engine reads the variable on each render rather than once when its module loads, so a test sets it in beforeEach, after its imports have loaded the engine, and the package’s bundle reads it the same way as the source does:
import { beforeEach, vi } from "vitest";
beforeEach(() => vi.stubEnv("GAME_ENGINE_VIEWS", "off"));A page has no process, so the variable changes nothing in a game’s build.
The vitest config names a setup file in setupFiles. The setup tells React the tests run under act, unmounts what the last test rendered, registers the jest-dom matchers, and stubs the scrollTo and matchMedia that jsdom lacks, answering matchMedia as a desktop. A game names @spawnite/testing/setup there, with @spawnite/testing as a dev dependency, and adds @spawnite/testing/setup to types in its test tsconfig to type the matchers. A game that needs more keeps a test/setup.ts, lists it after the package, and sets sequence: { setupFiles: "list" } so vitest runs the two in that order rather than in parallel. A game made by spawnite create from a template that declares @spawnite/testing comes with all of it; Holdfast’s template keeps its own test/setup.ts instead.
A stubbed fetch
Section titled “A stubbed fetch”A test of code that fetches, such as a panel that reads a page from the dev server, stubs fetch with stubFetch from @spawnite/testing/fetch. It takes one answer for every URL, or an answer per URL, keyed by the URL exactly as the code passes it. An answer is a Response, served as a fresh copy on each call, or a function that takes fetch’s own arguments. It returns the spy, so the test reads the calls, and it puts the real fetch back when the test ends:
// Excerpt of test/shots.test.tsimport { stubFetch } from "@spawnite/testing/fetch";
it("saves the shot through the dev server", async () => { const fetch = stubFetch({ "/__shots": Response.json({ file: "shots/1.png" }), }); await expect(saveShot(png)).resolves.toBe("shots/1.png"); expect(fetch).toHaveBeenCalledWith("/__shots", expect.anything());});A URL that no route names rejects, and fails the test even where the code catches the rejection, so stubFetch({}) proves the code fetched nothing. A function answer covers the rest: a network failure, () => Promise.reject(new TypeError("offline")), or a request held in flight, () => new Promise(() => {}). Call it in the test or in a beforeEach.
The mocked canvas hands the engine a renderer that cannot compile shaders ahead, and the engine reads that as a canvas that runs no frames. The loading screen then waits on nothing a frame does, neither the room’s welcome nor a drawn frame, and with the views off it waits on no drawn character or ground. It lifts once the physics, navmesh and scatter shapes chunks have landed and the scene has mounted, so the test finds the lobby’s Play button and every Hud.
A temp folder
Section titled “A temp folder”A test that writes files, such as a save or a generated game, makes its folder with makeTempDir from @spawnite/testing/temp and never removes it:
import { makeTempDir } from "@spawnite/testing/temp";import { it } from "vitest";
it("writes the save", () => { const folder = makeTempDir("save-"); // ...});Called in a test or a beforeEach, the folder goes when that test finishes, passed or failed. Called at a file’s or a describe block’s top level, it goes when that file or block finishes, or with the file when the block is skipped or filtered out. A file whose every test is skipped or filtered out runs no hook, so its folders stay unless the run’s global setup is this repository’s vitest.temp-guard.ts, which removes them at the run’s end. Not in a beforeAll, whose folder nothing removes: call it at the block’s top level instead. A second argument names a parent folder other than os.tmpdir(), for a test whose files must sit inside the workspace.
A model file
Section titled “A model file”@spawnite/testing/model writes a rigged figure as a GLB, for a test that needs a model file: boxes skinned to named bones, in metres with y up, and clips that each turn one bone from its rest pose:
/** A two-bone figure: a box a bone, and a clip that bends the spine. */const figure: WriteFigureOptions = { bones: [ { name: "Hips", head: [0, 0.8, 0] }, { name: "Spine", head: [0, 0.9, 0], parent: "Hips" }, ], boxes: [ { bone: "Hips", centre: [0, 0.85, 0], size: [0.3, 0.1, 0.2] }, { bone: "Spine", centre: [0, 1.1, 0], size: [0.3, 0.4, 0.2] }, ], clips: [ { name: "bend", bone: "Spine", seconds: 1, rotation: [0, 0, Math.SQRT1_2, Math.SQRT1_2], }, ],};await writeFigure(file, figure) writes the file, with writeFigure and the WriteFigureOptions type imported from @spawnite/testing/model.
A bone’s parent comes before it, and rotation is a quaternion, x, y, z, w. A clip’s translation also moves its bone from its rest place, and a box’s also binds it to a second bone by a share, { bone, weight }, for a test of partly bound vertices.
Property tests
Section titled “Property tests”A property test states what holds for every input, and fast-check draws the inputs: hundreds of them, biased toward the edges such as 0, -0, the smallest double and a __proto__ key. When one fails, fast-check shrinks it to the smallest input that still fails and prints it. Write one where a rule is short and the inputs are many: a round trip, such as a decode of an encode or a save read back after a write, or a law, such as a sine that is odd.
Add fast-check and @fast-check/vitest as dev dependencies, and pass a fixed seed and numRuns, so every machine draws the same inputs:
import { fc, test } from "@fast-check/vitest";import { expect } from "vitest";import { quaternionToYaw, yawToQuaternion } from "@spawnite/engine";
test.prop([fc.double({ min: -3.14, max: 3.14, noNaN: true })], { seed: 2640, numRuns: 200,})("reads back the yaw it wrote", (yaw) => { expect(quaternionToYaw(yawToQuaternion(yaw))).toBeCloseTo(yaw, 12);});A failure prints the counterexample, with the seed and path that replay it alone. The engine’s own property tests sit beside its other tests, such as the codec’s in packages/engine/test/gameplay/replication/codec.test.ts.