Skip to content

Testing ​

Twinstate's guarantees are only as good as the checks that hold them. The test kit is part of the core: it is how an application proves it uses the rest correctly. Its checks run every kind, mutation and entry in your app, and the types make sure none is left out.

ts
import { describeTwin, testId } from 'twinstate/testing';

describeTwin(twin, {
  server: () => makeServer(memoryDb()), // createTwinServer(…) without a transport: the kit attaches its own
  fixtures: {
    // one per mutation — required by the type: a new mutation does not compile until it has one
    pinNote: {
      given: (t) => t.seed(note, testId(note, 'n1'), aNote),
      args: { id: testId(note, 'n1'), pinned: true },
    },
    createNote: {
      args: { id: testId(note, 'n2'), title: 'Plans' },
      serverComputed: ['note.updatedAt'], // fields the server may set differently from the effect
    },
    updateSettings: { args: { patch: { sort: 'title' } } },
  },
  dataset: representativeData, // for the snapshot budget, required
  snapshotBudget: 200_000, // bytes, required
  invariants: [(snap) => everyNoteHasABody(snap)], // your app's own facts, checked after every step
  entries: import.meta.glob('../src/**/*.tsx', { eager: true }), // every module that declares entries
  entryFixtures: {
    // one per entry, by name: the state to render it in, and its props
    noteScreen: {
      given: (t) =>
        t.seed(note, testId(note, 'n1'), aNote).seed(noteBody, testId(note, 'n1'), aBody), // everything its loads read
      props: { id: testId(note, 'n1') },
    },
  },
});

describeTwin registers every check below as tests in your runner, so a check added to Twinstate later runs without anyone adding it. It runs your real handlers and store against an in-memory transport — attached with serve, as a real one would be — with as many simulated clients as a check needs.

Fixtures are yours, and required. Arguments generated from a schema cannot satisfy a mutation's preconditions — that the record exists, that validate passes — so each mutation's fixture supplies a state (given) and arguments that succeed. The fixtures' type is a mapped type over the registry's mutations, so the compiler lists any mutation without one. A fixture may add rejects cases, each naming a declared reason, so every rejection path runs too, and serverComputed, the fields the server may legitimately set differently from the effect (typed 'kind.field').

Values are made, never cast. testId(kind, 'n1') makes a branded id and testPreload(Entry, props) a preloaded for rendering an entry in a component test, so tests pass the same no-unsafe-type-assertion rule as the app.

Entries register themselves. Every entry(...) is recorded, in tests only, and describeTwin imports the modules entries names, so none is missed. Entries are not in the registry, so their fixtures cannot be exhaustive by type: instead, an entry recorded without an entryFixtures entry is a failing test that names it, and so is a duplicate entry name. A fixture must make every load present: an entry whose load came back absent renders its absent element instead of its component, and checkEntries fails that fixture rather than pass without rendering (maybe loads excepted).

The invariant suite ​

Every check runs on Twinstate's in-memory test server except checkStore, which runs against your real store adapters — pointed at a temporary directory or a test database — because only they know how your data is stored, and no type can see your files or tables.

checkwhat it proves
checkRegistrythe graph rules the types cannot express: no ref cycles; no .catch and no undefined in any field, at any depth; every object in a mutation's arguments strict (z.strictObject), at any depth; and every kind's values plain JSON at any depth, recursive ones included (the compiler stops looking after a few levels)
checkReplayapplying every broadcast, in order, from an empty replica, produces exactly the server's records as a client sees them (without serverOnly fields) — after every step of every fixture. A patch that was dropped or misapplied fails here
checkConvergenceper mutation: client A mutates → A's replica, B's replica and the server's snapshot are equal
checkIntegrityafter every step, every ref in every replica resolves, every link to an instant record resolves to its record or to null, and removing a parent removes its children and the records keyed by its id from every replica
checkInvariantsyour invariants, after every step of every fixture and every generated interleaving — derived facts ("a draft with text has hasContent") hold whichever mutation ran, including ones added later
checkResendevery mutation, sent twice, applies once — with another client's write in between, with the record removed in between, and across a server restart (the durable record of applied ids answers it); a write failed in the middle of the turn, then the resend after the restart, finishes the job (handlers are safe to re-run over their own partial result); with a store that has no transaction, a crash between the turn's data and its ids leaves a resend that runs again without harm to updates and merges (the create-after-remove residual is exercised and documented, not hidden); a resend registers no second onCreated work; merges are idempotent
checkEffectsfor every mutation that has an effect (one without shows a "sending" state instead, and is skipped): the effect is deterministic (run twice on the same input, same output), and agrees with its handler: what the display showed just before done equals the replica just after it, on every record either the effect or the handler touched, except the fixture's serverComputed fields. (Purity — reading nothing but its arguments — is the lint rule's job)
checkOrderingtwo clients' mutations interleaved in every order: each client's done follows its own data, and every client ends on the server's final state
checkTurnsevery handler finishes within 100ms and never hangs; a tx used after its turn ended throws; a tx.reject rejects its turn even when the handler catches the throw
checkValidationper kind with a validate hook: a change that fails it rejects its mutation and leaves the record, the store and every replica untouched — including the changes, emits and follow-up work of the same turn, and even when the handler caught the error (a turn commits all or nothing, in memory and on every device)
checkVisibilityserverOnly fields never appear in any snapshot, patch or client type; memoryOnly fields are never written to the store and start from their default after a restart
checkEntriesevery entry renders from its preload; a client.preload started while React is rendering fails, naming the entry (the indirect cases the lint rule cannot see); a preload nothing renders is released after its TTL, so nothing leaks
checkStorefor every kind, a record written through the adapter and loaded back is the same record, meta included — the one thing the adapter's types cannot check; after a parent's remove, none of its children (or records keyed by its id) loads any more; sample records of every older version, from your test dataset, load through the kind's migrate steps into values the current schema accepts, and their next write goes through update, whole; a record written back by older code keeps its newer stamps, and loses its retired fields on the next load; unknown fields written by newer code survive a load and a write; the twinstate adapter round-trips a value, keeps each record apart, lists them, and removes one; the registry matches twinstate.lock.ts (so a schema change is always re-locked on purpose)
checkSnapshotBudgetthe instant snapshot for your dataset stays under snapshotBudget
checkWindowsfor every kind that declares query: a window stays equal to the same query run fresh, after every step — records entering, leaving and moving as they change on any device, loadMore widening it, and across a reconnect, a reset and a server restart; windows over one parent's children likewise
checkCachea client started from a cache, after every step, ends equal to a client started fresh — across a server restart (new epoch), a ring overrun, and a record deleted while it was closed; a topic saved under another cache key is never rendered, but deleted and refetched — and only topics holding a changed kind are; a stopped tab (outdated or incompatible) writes no cache and adopts nothing; a topic of a dropped kind is deleted at the next startup; a topic under another key is overwritten whatever its position and evicted before the tab's own when over budget; two tabs writing one topic leave the newer position; after clearCache no open tab, the caller included, writes the cache again
checkTransporton a transport pair you pass in (the kit's own by default): interleaved requests and broadcasts across several connections arrive in order, and a done reaches only its sender
checkRestartthe server restarted mid-run, including in the middle of follow-up work: every client resets once and converges; your invariants still hold after boot (so "a job still running with no process behind it" is caught)
checkFollowUpsevery afterEveryCommit follow-up run twice, and twice at once, with the same inputs, against fakes that honour idempotency keys; every from: 'server' mutation sent with a key applied twice and in reverse order; each ends on the same state as a single run, so a missing key or guard fails, naming the follow-up
checkShutdownserver.close() in the middle of every follow-up: client mutations are refused and stay in their outboxes, the follow-up's result, reported after the close, is saved in the server's outbox and applied once by the next process, and every client resets once and converges; with a stub outbox that notifies, the partition starts elsewhere at once and applies the result while it runs

Also covered ​

  • Reconnect and reset: resume from the ring, reset on a new epoch, reset on a position older than the ring, a reset removing records deleted while away — each tested as thoroughly as the others, because every server restart takes the reset path. A lazy topic opened while other topics are far ahead starts from its own snapshot.
  • Appends: a stream of appends applied to a replica equals the final text; an append with a wrong at triggers a reset instead of corrupting text.
  • The outbox: entries survive a simulated process kill once written; nothing is sent before its write commits; hiding the page flushes pending writes; a tab that stops waits for its pending writes before releasing its locks; a patch coalesces only into the last entry (a patch typed after a different mutation is appended, never moved ahead of it); a burst of patches to one field produces one send per 300ms pause; entries older than 24 hours are held, not sent, and reach the outbox UI; releasing them sends them in order, applied at most once even across a server restart; entries written by an older revision are parsed strictly after an upgrade; on one device, a tab claims its revision only on its first ready, before it re-subscribes, sends or writes the cache; a tab that sees a higher live revision, or whose hello is answered incompatible or that receives a record it cannot parse, stops for good the same way (a single subscribe or mutate answered incompatible refuses only that one) — its revision lock, every outbox lock it holds (adopted ones included) and its waiting requests released, read-only (outdated or incompatible, a mutate refused with that reason and nothing written, no cache writes); a tab queries the live revisions at start, so one opened offline after a newer tab announced stops too; a granted outbox written by a newer revision, or granted to a stopped tab, is released untouched; the server rejects an unknown argument key instead of stripping it — an unknown key holds the entry, a newly defaulted argument does not — and an entry of an older format is held, not sent.
  • Events: delivered inside their topic's message, after its ops; an event emitted on a lazy root reaches only that topic's watchers; after a short gap, a reconnect's resume replays the missed ones younger than their maxAge once, in order, and a reset, a restart or a first subscribe (a cache resume, a lazy root opened again) replays none; with perDevice, one tab of several handles each event, replayed or not; removing an event keeps older revisions connected.
  • Update, flush and effect performance: a benchmark applies a representative burst of updates over thousands of records, with pending effects re-applied on every replica change, and fails if it exceeds a budget, so "cost grows with changes, not with data" stays true.

Type tests ​

The compile-time guarantees are tested too, as // @ts-expect-error cases the package's typecheck runs: every row of the server's "what the compiler enforces" table, the declaration rules in concepts, and the React rules (rendering an entry without preloaded, another entry's preloaded, a lazy read without a handle, an absent element missing where a load can be absent). A claim in these docs that no type test proves is a bug in the docs.

Writing your own tests ​

ts
test('a pinned note shows on the other device', async () => {
  const [a, b] = t.clients(2);
  await a.mutate(twin.mutations.pinNote, { id, pinned: true });
  expect(b.read((s) => s.note.get(id)?.pinned)).toBe(true);
});

test('offline typing survives a kill', async () => {
  const a = t.client({ online: false });
  a.mutate(twin.mutations.updateNoteBody, { id, patch: { text: 'draft' } });
  const revived = a.kill().relaunch({ online: true });
  await revived.settled();
  expect((await t.server.get(noteBody, id))?.text).toBe('draft');
});

A test client has the same names as the real one (mutate), and the server is the real server (get), so nothing learned in a test has to be unlearned in the app.