# @irtio/testing

> Reference for the testing library that runs rooms in process with test clients and a controlled clock.

`@irtio/testing` runs your room definition in process with no network: a
room host, the router and storage it talks to, and test clients that use
the real `@irtio/client` over an in-memory transport. Time moves only when
the test moves it. It works with Vitest and `node:test`; `irt test` runs
Vitest. [Testing rooms](/docs/guides/testing) shows patterns for
hibernation, crashes, calls, ownership and migrations.

```ts
import { createTestHost, testRoom, RoomStoppedError, TestClock, type TestHost, type TestRoom, type TestClient, type TestRoomOf, type TestClientOf } from "@irtio/testing";
```

## Starting rooms

```ts
function testRoom<S, P, D, C>(def: RoomDefinition<S, P, D, C>, opts?: TestHostOptions): TestRoom<S, P, D, C>;
function createTestHost<S, P, D, C>(def: RoomDefinition<S, P, D, C>, opts?: TestHostOptions): TestHost<S, P, D, C>;

interface TestHostOptions {
  project?: string;           // defaults to "test"
  config?: {                  // irt.config.ts's default export
    settings?: ProjectSettings;
    rooms?: Record<string, string | { size?: string; maxPlayers?: number; retention?: string }>;  // as irt.config.ts declares them
  };
  type?: string;              // def's room type in config.rooms; defaults to "default"
  settings?: ProjectSettings; // as irt.config.ts declares them, instead of config.settings; rooms.retention applies
  startAt?: number;           // the clock's wall time at the start, ms since the epoch; defaults to the real time
  types?: Record<string, RoomDefinition>;  // the build's other room types, beside def as default, such as a lobby's target
}
```

The host doesn't read `irt.config.ts` itself: without `config` or
`settings`, a test room runs with every setting at its default, such as
no data collections and 64 players. Pass the config to test with the
project's own:

```ts
import config from "../irt.config.js";

const t = testRoom(match, { config, type: "match" });
```

`config.settings` applies unless `settings` is given. A room type's
`size`, `maxPlayers` and `retention` in `config.rooms` apply to the
host's type of the same name: the definition's from `type`, and each
of `types` by its name. A `type` that `config.rooms` doesn't name, or
one given without `config`, throws.

A test that checks absolute times, such as `onWake`'s `savedAt`,
`room.now()` or a schedule on the UTC clock, should pass `startAt`, since
the default changes from run to run.

```ts
// For typing helpers that take a test room or client of a room definition:
type TestRoomOf<typeof room> = TestRoom<S, P, D, C>;
type TestClientOf<typeof room> = TestClient<S, P, C>;
```

`settings.rooms.retention` applies: a room that stays hibernated for its
retention is deleted, and its `status` becomes `"not created"`. The test
host deletes it the moment the retention passes; deployed, the sweeper
does it up to an hour later.

`testRoom(def)` is a host with one room called `"room"` in project
`"test"`. Use `createTestHost` for several rooms of the same build in one
room host, such as to check that one room's crash leaves the others
running.

`S` and `P` are the schema's state and private kinds, `D` the type of
`room.data`, and `C` the schema's calls. To type a helper that takes a
test room or client, use `TestRoomOf<typeof room>` and
`TestClientOf<typeof room>` rather than writing the parameters out:
`TestClient<S, P>` leaves out `C`, which then defaults to no calls, so
`client.call` takes `never`.

```ts
// helpers.test.ts
import { CallRejected, defineCalls, defineRoom, defineSchema, entity } from "@irtio/room";
import { type TestClientOf, type TestRoomOf, testRoom } from "@irtio/testing";
import { expect, test } from "vitest";

const Table = entity("table", { seated: "u8" });
const room = defineRoom({
  schema: defineSchema({ state: Table, calls: defineCalls<{ sit(args: { seat: number }): { seat: number } }>() }),
  calls: {
    sit({ seat }, { room }) {
      if (seat > 4) throw new CallRejected("the table has 4 seats");
      room.state.seated += 1;
      return { seat };
    },
  },
});

async function sit(t: TestRoomOf<typeof room>, client: TestClientOf<typeof room>, seat: number): Promise<number> {
  return (await t.settle(client.client.calls.sit({ seat }))).seat;
}

test("two players sit", async () => {
  const t = testRoom(room);
  expect(await sit(t, await t.connect({ player: "alice" }), 1)).toBe(1);
  expect(await sit(t, await t.connect({ player: "bob" }), 2)).toBe(2);
  expect(t.live.state.seated).toBe(2);
});

test("a fifth seat is refused", async () => {
  const t = testRoom(room);
  await expect(sit(t, await t.connect({ player: "carol" }), 5)).rejects.toThrow("the table has 4 seats");
});
```

The reply to a call that changed room state waits until the change is
saved, which in a room with a `tickRate` is the next tick, so `sit`
passes the call to `settle`, which moves the clock until the reply
arrives and resolves or rejects as the call does. A helper that starts
a call, moves the clock, and only then awaits it leaves a rejected call
without a handler meanwhile, and Vitest reports an unhandled rejection;
`settle` handles the call while the clock moves.

## TestHost

```ts
class TestHost<S, P, D, C> {
  readonly clock: TestClock;
  readonly tickRate: number;                  // 0 for a room without ticks
  room(id: string): TestRoom<S, P, D, C>;     // a handle; the room starts on connect or wake()
  tick(n?: number): Promise<void>;      // runs n ticks (default 1) of the room's tick rate; throws without one
  advance(ms: number): Promise<void>;   // moves the clock, running every timer that falls due
  crash(): Promise<void>;               // crashes the room host; its rooms restart from room state
  // What a game without a backend calls from its client, against this host:
  createRoom(opts?: { id?: string; public?: boolean; joinCode?: boolean; meta?: unknown; maxPlayers?: number }): Promise<{ id: string; joinCode: string | null }>;
  joinByCode(code: string): Promise<string>;
  listPublic(): Promise<{ id: string; players: number; meta: unknown }[]>;
  quickJoin(opts?: { meta?: Record<string, unknown>; maxPlayers?: number }): Promise<{ id: string; joinCode: string | null }>;
  // Player data, collections and leaderboards, kept in memory for the host:
  playerData(player: string): PlayerData;   // as the server API, to seed and assert; nothing cached
  collection(name: string): Collection;
  leaderboard(name: string): Leaderboard;
  query(op: { op: string; [arg: string]: unknown }, caller?: DataCaller): Promise<DataReply>;  // one raw operation, as the server API by default
  dataClient(opts?: { player?: string }): DataClient;  // @irtio/client's dataClient, as a player or a new guest, with no room
}

class TestClock {
  now(): number;                        // ms since the host was created
  wall(): number;                       // the host's startAt plus now(); room.now() reads it
  jump(ms: number): void;               // moves time without running timers, like a blocked event loop
}
```

**Ticks.** `tick(n)` moves the clock by `n / tickRate` seconds, and every
running room runs exactly `n` ticks in it, so `room.live.tick` grows by
exactly `n`. A room without a `tickRate` has no ticks, and `tick` throws
for it: "the room has no tickRate, so it has no ticks to run". Move its
clock with `advance(ms)`, or wait for what's pending with its
`settle()`. Inside `onTick`, `room.tick` is the number of the tick
running: 1 for a new room's first tick (see
[Ticks](/docs/room/sdk#ticks)). `connect` moves the clock too,
until the client holds its first state update, so it may run a tick of
a running room. To time something the room started, read when it
started from the room rather than counting ticks since `connect`:

```ts
// round.test.ts
import { defineRoom, defineSchema, entity } from "@irtio/room";
import { testRoom } from "@irtio/testing";
import { expect, test } from "vitest";

const Round = entity("round", { phase: "string", endsAt: "u32" });
const room = defineRoom({
  schema: defineSchema({ state: Round }),
  tickRate: 20,
  onTick(room) {
    if (room.state.phase === "" && room.connections.size >= 2) {
      room.state.phase = "playing";
      room.state.endsAt = room.tick + 60 * 20;
    } else if (room.state.phase === "playing" && room.tick >= room.state.endsAt) {
      room.state.phase = "ended";
    }
  },
});

test("a round lasts exactly 60 seconds", async () => {
  const t = testRoom(room);
  await t.connect({ player: "alice" });
  await t.connect({ player: "bob" });
  await t.host.tick();
  expect(t.live.state.phase).toBe("playing");
  await t.host.tick(t.live.state.endsAt - t.live.tick - 1);
  expect(t.live.state.phase).toBe("playing");
  await t.host.tick();
  expect(t.live.state.phase).toBe("ended");
});
```

**Local-mode API.** `createRoom`, `joinByCode`, `listPublic` and `quickJoin` behave as
the [client SDK's](/docs/client/sdk#room-wide-requests-for-games-without-a-backend)
do against `irt dev`, with the host's `settings` applied: they reject
with an `IrtError` whose `code` is the HTTP status, such as 403 when
`players.createRooms` is off or 404 for an unknown join code, and
`joinByCode` takes a code in any case. `quickJoin` holds each slot it hands
out until a client connects to the room or the host's clock passes 10
seconds. Connect to a created room with `host.room(id).connect()`.
`host.room(id).connect()` creates a room that doesn't exist only when
`players.createRooms` is on, as the router does; with it off the connect
fails with 4002 until the room is created or `wake()` starts it. A
room's `maxPlayers` closes connections past it with 4003.

**Player data.** Each host keeps player data, collections and
leaderboards in memory, with the `data` settings of its `settings` and
the host's clock for entries' times and leaderboard periods. Seed and
read it with `host.playerData(player)`, `host.collection(name)` and
`host.leaderboard(name)`, which call as the server API would and cache
nothing. Room code's calls go through the same store, with the room's
5-second cache, so after a test writes a key a room read in the last 5
seconds, move the clock with `host.advance(5000)` or have the room call
`refresh()`. A test client's `client.client.playerData`, `collection`
and `leaderboard` make client calls, with the client's rights, as
`host.dataClient()` does without a room. Pass `startAt` to pin the week
a leaderboard test runs in.

```ts
// highscore.test.ts
import { defineRoom } from "@irtio/room";
import { createTestHost } from "@irtio/testing";
import { expect, test } from "vitest";

const room = defineRoom({
  async onJoin(room, conn) {
    const visits = await room.playerData(conn.player).increment("visits", 1);
    await room.leaderboard("visits").submit(conn.player, visits);
  },
});

test("each join counts a visit and ranks the player", async () => {
  const host = createTestHost(room, { settings: { data: { collections: { visits: { clientRead: true, leaderboard: {} } } } } });
  await host.playerData("bob").set("visits", 4);
  await host.room("lobby").connect({ player: "ada" });
  const bob = await host.room("lobby").connect({ player: "bob" });
  expect(await host.playerData("bob").get("visits")).toEqual({ value: 5, version: 2 });
  expect(await bob.client.leaderboard("visits").around()).toMatchObject({ rank: 1, entries: [{ player: "bob" }, { player: "ada" }] });
});
```

`tick` and `advance` throw a `RoomStoppedError` when a room stopped
meanwhile, from an error in `onCreate`, `onWake`, `onTick`,
`onHibernate`, the stepper, interest or a migration, or from room state
over 32 MB:

```text
Room test/duel stopped at tick 12:
Error: score overflow
    at onTick (src/room.ts:20:11)
Other rooms in the room host keep running. If the test expects this, catch it, for example `await expect(host.tick()).rejects.toThrow(RoomStoppedError)`.
```

Errors in `onMessage`, `onLeave` and `onRequest` don't stop the room;
they're logged to stderr and the message is dropped.

`crash()` drops the room host without running any hooks, as a crash
would. Its rooms restart in a new room host from the room state the
parent holds, which includes every change the room sent, and their
clients reconnect the next time the clock moves.

## TestRoom

```ts
class TestRoom<S, P, D, C> {
  readonly id: string;
  readonly host: TestHost<S, P, D, C>;
  readonly clients: TestClient<S, P, C>[];
  readonly status: "starting" | "waking" | "active" | "hibernating" | "hibernated" | "stopped" | "not created";
  readonly live: Room<S, P, D>;            // the running room; read and write its entities from the test
  stored(): RoomData;                   // the room state a wake would start from, decoded
  connect(opts?: { player?: string; meta?: unknown; type?: string }): Promise<TestClient<S, P, C>>;  // type: one of the host's types
  settle(): Promise<void>;              // moves the clock until the host's clients have no calls in flight or writes to send, and hold the state that followed
  settle<T>(pending: Promise<T>): Promise<T>;  // the same, waiting for pending too, such as a call, and resolving or rejecting as it does
  wake(): Promise<void>;                // starts or wakes the room with no connection
  hibernate(): Promise<void>;           // hibernates now; connected clients close with 4011
  request(message: unknown): Promise<unknown>;  // calls onRequest, as the server API does, and resolves with its reply
  replays(): string[];                  // the room's replay IDs, oldest first
  clips(): string[];
  replay(id: string): Replay;           // loads a replay, as recorded so far, with @irtio/client/replay
  clip(id: string): Replay;
}
```

- `connect` without `player` joins as a guest. `meta` becomes the token's
  `meta` claim, which `onJoin` reads as `connection.meta`. It moves the
  clock until the client holds its first full state update, which a
  running room sends once `onJoin` has run. When the room refuses the connection it rejects
  with an `IrtError` whose `code` is the close code, as `connect` from
  `@irtio/client` does: `await expect(t.connect({ player: "c" })).rejects.toMatchObject({ code: 4003 })`.
- `live` throws if the room isn't active, saying its status.
- `settle` waits on every test client of the host, and the clients
  their handoffs connected, not only this room's. It moves the clock a
  step at a time: a tick in a room with a `tickRate`, or 50 ms in a room
  without ticks, so alarms and other timers due in that time run. It
  takes at least one step, and ends with a step that began with nothing
  pending, so each write sent before it has been applied and its changes
  sent. It throws after 100 steps, listing what is still pending, such
  as a call whose handler never returns; use `tick` or `advance` to move
  the clock past a call's timeout instead.
- `hibernate` waits for an async `onHibernate` in real time, up to 10
  seconds, so one that waits on real I/O, such as a `fetch` to a backend
  the test runs, finishes first. The test clock doesn't move meanwhile.
  If it hasn't finished by then, `hibernate` rejects, saying the room
  is still hibernating.
- `request` wakes the room first if it isn't active, as a server API
  message does. It rejects with the error when `onRequest` throws, when
  the room has no `onRequest`, and when the room stops or its room host
  crashes before `onRequest` returns. An `onRequest` that calls
  `room.requestHibernate()` resolves with its reply, and the room
  hibernates after it.
- A room with no connections hibernates by itself 30 seconds after the
  last one closes, as it does in production.
- `replay` and `clip` load with the room definition's schema and the
  host's clock, so `play()` moves as the test moves time. They throw,
  listing the IDs the room has, for an ID it doesn't.

## TestClient

```ts
class TestClient<S, P, C> {
  readonly client: ReadyRoomClient<S, P, C>;  // the real client, ready; everything in the client SDK works
  readonly private: ClientEntity<P>;   // this player's private state as the client holds it
  readonly messages: { message: unknown; unreliable: boolean; tick: number }[];
  readonly events: string[];           // "waking", "reconnecting 1006", "open" after a reconnect, "close 4011", "handoff <room>", ...
  readonly handoffs: Handoff[];        // each handoff that moved the player: the new room and its client, or the error
  reconnects: number;                  // reconnects that completed, each an open with reconnected true
  closedWith: number | undefined;      // the close code once the connection ended for good
  readonly lastUpdate: { update: number; tick: number; parts: number; bytes: number; full: boolean } | undefined;  // see below
  readonly speakers: readonly string[];   // player IDs this client hears, as the room's voice rule last said
  readonly listeners: readonly string[];  // player IDs that hear this client
  view<K extends Kind>(kind: K): Record<string, unknown>[];  // entities it sees, as plain objects sorted by ID
  sees(id: number): boolean;
  expectSees(id: number): void;
  expectNotSees(id: number): void;
  expectMessage(expected: unknown): void;   // objects match when every key of `expected` matches
  send(message: unknown, opts?: { unreliable?: boolean }): void;
  predict<I, K>(stepper: Stepper<I>, opts: { find(room: RoomClient<S, P, C>): ClientEntity<K> | undefined; sample(prediction: Prediction<I, K>): I }): Prediction<I, K>;
  drop(opts?: { reconnect?: boolean }): void;  // drops the network, onLeave's left false; the client reconnects with backoff unless reconnect is false
  reconnected(): Promise<void>;        // moves the clock until resynced since the last drop or crash; at once if it already is
  close(): Promise<void>;              // client.close(): onLeave's left is true, and presence ends at once
}
```

- `speakers` and `listeners` are the client's `room.peers`, empty until
  the room's [voice](/docs/room/voice) rule first tells it.
- `lastUpdate` is `client.stats.lastUpdate`, the last whole state
  update the client applied; `client.stats` has the client's other
  traffic too, by message type (see
  [Wire statistics](/docs/client/sdk#wire-statistics)).
  In it, `update` is its update number, `tick` its tick (0 in a room
  without ticks), `parts` how many messages it was split into, each
  at most about 60 KB, `bytes` their total size as sent, and `full`
  whether it was a full update, as on joining or reconnecting, rather
  than a delta. A state update that sends the client nothing leaves it
  as it was. It's undefined until the first.

Use `lastUpdate` to check what a game costs on the wire, such as that a
join splits into parts and an edit sends a few bytes:

```ts
// sync-size.test.ts
import { defineRoom, defineSchema, entity, type RoomEntity } from "@irtio/room";
import { testRoom } from "@irtio/testing";
import { expect, test } from "vitest";

const Chunk = entity("chunk", { blocks: "bytes" });
const room = defineRoom({
  schema: defineSchema({ entities: [Chunk] }),
  tickRate: 20,
  onCreate(room) {
    for (let i = 0; i < 8; i++) room.entities.create(Chunk, { blocks: new Uint8Array(32 * 32 * 32).fill(1) });
  },
  onMessage(room) {
    const chunk = room.entities.get(2) as RoomEntity<typeof Chunk>;
    chunk.patch("blocks", 0, new Uint8Array([0]));
  },
});

test("a join is split into parts and an edit is a few bytes", async () => {
  const t = testRoom(room);
  const alice = await t.connect({ player: "alice" });
  // Two 32 KB chunks don't fit in one part, so each gets its own.
  expect(alice.lastUpdate).toMatchObject({ full: true, parts: 8 });

  alice.send("dig");
  await t.settle();
  expect(alice.lastUpdate).toMatchObject({ full: false, parts: 1 });
  expect(alice.lastUpdate!.bytes).toBeLessThan(32);
});
```

Failure messages name the client, its connection, the room and the tick,
and say what it has instead:

```text
Expected client "alice" (connection 1) in room test/room to see entity 99 at tick 4, but it doesn't. It sees 3 entities: score 0, private 1, player 2.
```

## A complete test file

```ts
// room.test.ts
import { defineRoom, defineSchema, entity, grid, type RoomEntity } from "@irtio/room";
import { createTestHost, RoomStoppedError, testRoom } from "@irtio/testing";
import { describe, expect, it } from "vitest";

const Player = entity("player", { owner: "string", x: "f32", y: "f32" });
const Score = entity("score", { points: "u32" });

const room = defineRoom({
  tickRate: 20,
  schema: defineSchema({ state: Score, entities: [Player] }),
  interest: grid({ cellSize: 10, radius: 1, dims: "xy", around: (_room, c) => c.data.player }),
  onJoin(room, conn) {
    const at = (conn.meta as { x: number } | null)?.x ?? 0;
    conn.data.player = room.entities.create(Player, { owner: conn.player, x: at });
    room.send(conn, { welcome: conn.player });
  },
  onMessage(room, conn, message) {
    const p = conn.data.player as RoomEntity<typeof Player>;
    if (message === "right") p.x += 15;
    if (message === "score") room.state.points += 1;
  },
  onTick(room) {
    if (room.state.points > 2) throw new Error("score overflow");
  },
  onLeave(room, conn) {
    room.entities.delete(conn.data.player);
  },
});

describe("the room", () => {
  it("shows players to each other only when they are near", async () => {
    const t = testRoom(room);
    const alice = await t.connect({ player: "alice", meta: { x: 0 } });
    const bob = await t.connect({ player: "bob", meta: { x: 25 } });
    const bobId = bob.view(Player)[0]!.id as number;
    alice.expectNotSees(bobId);
    alice.send("right");
    await t.host.tick();
    alice.expectSees(bobId);
    alice.expectMessage({ welcome: "alice" });
  });

  it("keeps the score across hibernation, reconnects and crashes", async () => {
    const t = testRoom(room);
    const alice = await t.connect({ player: "alice" });
    alice.send("score");
    await t.host.tick();

    alice.drop();
    await alice.reconnected();
    expect(alice.client.state.points).toBe(1);

    await t.host.crash();
    await alice.reconnected();
    expect(alice.client.state.points).toBe(1);

    await t.hibernate();
    expect(alice.closedWith).toBe(4011);
    await t.host.advance(60_000);
    const back = await t.connect({ player: "alice" });
    expect(back.client.state.points).toBe(1);
    expect(t.stored().state.points).toBe(1);
  });

  it("stops only the room whose tick threw", async () => {
    const host = createTestHost(room);
    const a = await host.room("a").connect({ player: "alice" });
    const b = await host.room("b").connect({ player: "bob" });
    for (let i = 0; i < 3; i++) a.send("score");
    await expect(host.tick()).rejects.toThrow(RoomStoppedError);
    expect(a.closedWith).toBe(4007);
    await host.tick();
    expect(host.room("b").status).toBe("active");
    expect(b.client.readyState).toBe("open");
  });
});
```

## With node:test

Nothing in `@irtio/testing` depends on Vitest:

```ts
// counts.node-test.ts
import assert from "node:assert/strict";
import { test } from "node:test";
import { defineRoom, defineSchema, entity } from "@irtio/room";
import { testRoom } from "@irtio/testing";

const Counter = entity("counter", { n: "u32" });
const room = defineRoom({
  schema: defineSchema({ state: Counter }),
  onMessage(room) {
    room.state.n += 1;
  },
});

test("counts messages", async () => {
  const t = testRoom(room);
  const c = await t.connect({ player: "p" });
  c.send("+1");
  await t.settle();
  assert.equal(c.client.state.n, 1);
});
```

## Common mistakes

- **Asserting before the room has sent.** A room with a `tickRate`
  sends state updates at the end of each tick, and one without sends
  them as soon as its code yields. `await t.settle()` before reading a
  client's view, or `t.host.tick()` in a room with a `tickRate`.
- **Calling `tick` in a room without a `tickRate`.** It throws; use
  `settle()` or `advance(ms)`.
- **Counting ticks from `connect`.** `connect` may run a tick of a
  running room. Read `t.live.tick` and the tick the room stored, as the
  round test above does.
- **Using real timers.** `setTimeout` in a test doesn't move the room's
  clock. Use `tick`, `advance` and `settle`.
- **Forgetting `await`.** `tick`, `advance`, `connect`, `hibernate`,
  `wake`, `crash` and `reconnected` are async; without `await` nothing
  has happened yet.
- **Expecting clients to come back after `hibernate()`.** They are closed
  with 4011 and don't reconnect; connect a new client to wake the room.
- **Catching `RoomStoppedError` too broadly.** It means room code threw
  where that stops the room; assert on its message.
