Canica

canica/testing

testApp runs the app against an in-memory database; scenes drive its pages; seeds fill the storyboard.

Functions and values

testApp uploadAs MINUTE HOUR DAY defineSeed seedStartTime sampleImage fakeResizer runSeed missingId scene as visit click type choose upload see notSee meanwhile within role label text placeholder

testApp functionsrc/testing/index.ts

Run an app against an in-memory database. Synchronous; bugs (defects) throw; typed failures come back as { _tag: "Failure", error }.

const t = testApp(app)
const alice = t.as("alice")
alice.mutation("addTodo", { text: "milk" })
expect(alice.query("todos")).toMatchObject({ _tag: "Success", value: [{ text: "milk" }] })
const testApp = <T extends AnyApp>(app: T, options?: TestOptions<T>): TestApp<T> => …

uploadAs functionsrc/testing/index.ts

An upload as viewer (the HTTP route adds only the session check).

const uploadAs = async (engine: Engine, viewer: ViewerShape, file: Blob | Uint8Array | string, name?: string, type?: string) => …

MINUTE constsrc/testing/index.ts

const MINUTE = 60_000

HOUR constsrc/testing/index.ts

const HOUR = 60 * MINUTE

DAY constsrc/testing/index.ts

const DAY = 24 * HOUR

defineSeed functionsrc/testing/index.ts

Sample data for canica storyboard, created by calling your mutations (so every invariant your handlers enforce holds). Export it as default from server/seed.ts:

import { defineSeed } from "canica/testing"
import app from "./index.ts"

export default defineSeed(app, ({ as, advance }) => {
  const me = as("viewer")
  const room = me.mutationOk("createRoom", { name: "General" })
  advance(5 * MINUTE)
  as("Ana").mutationOk("send", { room, body: "Hi!" })
})
const defineSeed = <T extends AnyApp>(_app: T, seed: Seed<T>, options?: SeedOptions): Seed<T> => …

seedStartTime functionsrc/testing/index.ts

The time a seed asks the storyboard to run at (defineSeed(app, seed, { now })).

const seedStartTime = (seed: unknown): number | undefined => …

sampleImage functionsrc/testing/sample-image.ts

const sampleImage = (): Blob => …

fakeResizer functionsrc/core/files.ts

Tests: a resizer that counts its calls. It answers "not an image" unless the bytes start like a PNG, JPEG, GIF or WebP, and otherwise returns 6 bytes ("WEBP" and the width) as image/webp.

const fakeResizer = (): ImageResizer & { readonly calls: Array<{ readonly width: number; readonly type: string; readonly size: number }> } => …

runSeed functionsrc/testing/index.ts

Run a seed against an engine (used by the dev server).

const runSeed = async (engine: Engine, seed: Seed<any>, viewerId: string): Promise<SeedCaptures | undefined> => …

missingId functionsrc/testing/index.ts

A well-formed id of table that no row has: for "not found" tests.

const missingId = <T extends string>(table: T): Id<T> => …

scene functionsrc/testing/scene.ts

Run the app's pages through these steps. Needs a DOM: Canica's vite config runs app tests in happy-dom.

const scene = async (t: TestApp<any>, routes: RouteTable, ...steps: ReadonlyArray<Step>): Promise<void> => …

as functionsrc/testing/scene.ts

Act as this user from now on: signed in (in public apps a guest; { signedIn: true } for an account there). { signedIn: false }: a visitor who has not signed in (an app that needs it shows its sign-in screen). The page is reloaded.

const as = (name: string, options?: { readonly signedIn?: boolean | TestProfile }): Step => …

visit functionsrc/testing/scene.ts

Open a route: visit("/rooms/$room", { room }), or visit("/rooms/$room", () => ({ room })) for a value made earlier.

const visit = (path: string, params?: Lazy<Record<string, unknown>>): Step => …

click functionsrc/testing/scene.ts

const click = (target: Locator): Step => …

type functionsrc/testing/scene.ts

Replace a field's text. text may be a function, for a value made earlier.

const type = (target: Locator, text: Lazy<string>): Step => …

choose functionsrc/testing/scene.ts

Pick an option (by its label) in a select: choose(label("Paid by"), "Ana").

const choose = (target: Locator, option: Lazy<string>): Step => …

upload functionsrc/testing/scene.ts

Pick a file in a file input (<FileInput label="Image">): upload(label("Image"), new File([bytes], "cat.png", { type: "image/png" })). It is uploaded to the test app like a browser would.

const upload = (target: Locator, file: Lazy<File>): Step => …

see functionsrc/testing/scene.ts

Wait until it is on screen (count: exactly that many). Fails after 2 s with what the screen showed.

const see = (target: Locator, count?: number): Step => …

notSee functionsrc/testing/scene.ts

const notSee = (target: Locator): Step => …

meanwhile functionsrc/testing/scene.ts

Something else happens meanwhile, e.g. another user (uses your typed t): meanwhile(() => t.as("bob").mutationOk("send", { … })), or time passes and scheduled jobs run (awaited): meanwhile(() => t.advance(0)) delivers queued emails.

const meanwhile = (run: () => unknown): Step => …

within functionsrc/testing/scene.ts

Run steps inside one part of the page: within(role("dialog"), click(role("button", { name: "Add" }))).

const within = (target: Locator, ...steps: ReadonlyArray<Step>): Step => …

role functionsrc/testing/scene.ts

role("button", { name: "Send" }), role("heading", { name: /General/ }), role("dialog").

const role = (role: string, options?: RoleOptions): Locator => …

label functionsrc/testing/scene.ts

A form control by its label: label("Room name").

const label = (text: Lazy<string | RegExp>): Locator => …

text functionsrc/testing/scene.ts

Visible text, even split across elements: text("3-day streak") (the whole text of an element) or text(/streak/).

const text = (text: Lazy<string | RegExp>): Locator => …

placeholder functionsrc/testing/scene.ts

const placeholder = (text: Lazy<string | RegExp>): Locator => …

Types

TestResult TestUser SentEmail TestProfile TestApp TestOptions SeedContext SeedCaptures Seed SeedOptions ImageResizer Step Locator Id UserId

TestResult typesrc/testing/index.ts

The result of a query or mutation in tests. Bugs (defects) throw instead.

type TestResult<A, E = unknown> =
| { readonly _tag: "Success"; readonly value: A }
| { readonly _tag: "Failure"; readonly error: unknown extends E ? { readonly _tag: string; readonly [k: string]: unknown } : Serialized<E | InvalidArgs> }

TestUser interfacesrc/testing/index.ts

One simulated user. t.as("alice") always returns the same user for the same name.

interface TestUser<T extends AnyApp> {
  readonly viewer: ViewerShape
  query<N extends keyof Q<T> & string>(
    query: N,
    ...args: {} extends ArgsType<Q<T>[N]> ? [args?: ArgsType<Q<T>[N]>] : [args: ArgsType<Q<T>[N]>]
  ): TestResult<SuccessType<Q<T>[N]>, ErrorType<Q<T>[N]>>
  mutation<N extends keyof M<T> & string>(
    mutation: N,
    ...args: {} extends ArgsType<M<T>[N]> ? [args?: ArgsType<M<T>[N]>] : [args: ArgsType<M<T>[N]>]
  ): TestResult<SuccessType<M<T>[N]>, ErrorType<M<T>[N]>>
  /** Like `query`, but returns the value and throws (with the error) on failure. */
  queryOk<N extends keyof Q<T> & string>(
    query: N,
    ...args: {} extends ArgsType<Q<T>[N]> ? [args?: ArgsType<Q<T>[N]>] : [args: ArgsType<Q<T>[N]>]
  ): SuccessType<Q<T>[N]>
  /** Like `mutation`, but returns the value and throws (with the error) on failure. */
  mutationOk<N extends keyof M<T> & string>(
    mutation: N,
    ...args: {} extends ArgsType<M<T>[N]> ? [args?: ArgsType<M<T>[N]>] : [args: ArgsType<M<T>[N]>]
  ): SuccessType<M<T>[N]>
  /** Run an action (its `ctx.fetch` is the stub given to `testApp`). */
  action<N extends keyof Act<T> & string>(
    action: N,
    ...args: {} extends ArgsType<Act<T>[N]> ? [args?: ArgsType<Act<T>[N]>] : [args: ArgsType<Act<T>[N]>]
  ): Promise<TestResult<SuccessType<Act<T>[N]>, ErrorType<Act<T>[N]>>>
  /** Like `action`, but resolves to the value and rejects (with the error) on failure. */
  actionOk<N extends keyof Act<T> & string>(
    action: N,
    ...args: {} extends ArgsType<Act<T>[N]> ? [args?: ArgsType<Act<T>[N]>] : [args: ArgsType<Act<T>[N]>]
  ): Promise<SuccessType<Act<T>[N]>>
  /**
   * Upload a file as this user, like `useUpload()` does: `const image = await t.as("ana").uploadOk(new Blob(["…"], { type: "image/png" }), "cat.png")`,
   * then pass the id to a mutation. Fails with `FileTooLarge`, `StorageFull`, `Unauthenticated` or `Forbidden`.
   */
  upload(file: Blob | Uint8Array | string, name?: string, type?: string): Promise<TestResult<FileId, FileError>>
  /** Like `upload`, but resolves to the id and rejects on failure. */
  uploadOk(file: Blob | Uint8Array | string, name?: string, type?: string): Promise<FileId>
  /** This person uses the unsubscribe link in an email's footer: the app's next send to them fails with `Unsubscribed`. */
  unsubscribeFromEmails(): void
}

SentEmail typesrc/testing/index.ts

An email a test sent (t.emails()), as queued: delivery (to the outbox) happens when jobs run (t.advance).

type SentEmail<T extends AnyApp> = {
  [N in keyof EmailsOf<T> & string]: {
    readonly template: N
    /** The recipient's user id. */
    readonly to: UserId
    /** Their address (a test user's is `<name>@example.com`). */
    readonly email: string
    readonly props: EmailProps<EmailsOf<T>[N]>
    /** The rendered subject. */
    readonly subject: string
    /** Its id (what `send` returned; `status(id)` reads it). */
    readonly id: EmailId
    /** `queued` until jobs run (`await t.advance(0)`), then `sent` (as the app sees it: tests never send anything). */
    readonly status: EmailState
    /** Why it failed (`status: "failed"`). */
    readonly reason: EmailFailure | null
    /** Tries so far. */
    readonly attempts: number
    /** The whole email as the recipient sees it: HTML and plain text (the app's name, the body, the footer). */
    render(): { readonly html: string; readonly text: string }
  }
}[keyof EmailsOf<T> & string]

TestProfile interfacesrc/testing/index.ts

A signed-in test user's profile; hd is their Google Workspace domain (for org apps' domains).

interface TestProfile extends Profile {
  readonly hd?: string
}

TestApp interfacesrc/testing/index.ts

interface TestApp<T extends AnyApp> {
  readonly engine: Engine
  /**
   * A user identified by `name` (hashed, so any string works and distinct names never collide). Signed in (profile
   * name "alice", email "alice@example.com"), except in public apps, where it is a guest unless
   * `{ signedIn: true }`. `{ signedIn: false }`: a visitor who has not signed in. `{ signedIn: { email, hd } }`:
   * that profile (`hd`: their Google Workspace domain, for `org` apps).
   */
  as(name: string, options?: { readonly signedIn?: boolean | TestProfile }): TestUser<T>
  /**
   * Move the clock forward (mutations see it through `Now`), running the scheduled jobs and crons due on the way,
   * each at its time. Mutations run before it returns; `await` it when actions may run.
   */
  advance(ms: number): Promise<void>
  /** Set the clock (epoch ms). */
  setTime(ms: number): void
  /** The clock (epoch ms); scenes show pages at this time. */
  now(): number
  /** The clock's day, "YYYY-MM-DD" (local time, like `useToday()`). */
  today(): string
  /** Run an internal mutation (`app({ internal })`) as `canica run` would. */
  run(name: (keyof T["internal"] | keyof T["mutations"]) & string, args?: unknown): TestResult<unknown>
  /** Run an action, internal ones too, as the system user. */
  runAction(name: keyof T["actions"] & string, args?: unknown): Promise<TestResult<unknown>>
  /** Scheduled jobs not run yet (`runAfter` and crons), earliest first. */
  jobs(): ReadonlyArray<{ readonly name: string; readonly at: number; readonly args: unknown; readonly cron: string | null }>
  /**
   * Call an endpoint (`/api/…`), as a webhook would: `await t.fetch("/api/stripe", { method: "POST", body, headers })`.
   * Or request a file link from a query's result (`/_canica/files/<id>?…`), as a browser would, at the test clock:
   * `const res = await t.fetch(todo.imageUrl)`. Then `res.status`, `res.headers`, `await res.json()`.
   */
  fetch(url: string, init?: RequestInit): Promise<Response>
  /** The emails the app sent (from mutations and actions that committed), oldest first. */
  emails(): ReadonlyArray<SentEmail<T>>
}

TestOptions interfacesrc/testing/index.ts

interface TestOptions<T extends AnyApp = AnyApp> {
  /** The clock's start (epoch ms). Default 2026-01-15 12:00 UTC. */
  readonly now?: number
  /** Seed for `Random`. */
  readonly seed?: number
  /**
   * What actions' `ctx.fetch` answers. Without it, a fetch fails the test (no network in tests):
   * `fetch: (url) => Response.json([{ title: "Bug" }])`.
   */
  readonly fetch?: (url: string, init?: RequestInit) => Response | Promise<Response>
  /** `ctx.secrets` for actions. */
  readonly secrets?: Readonly<Record<string, string>>
  /**
   * Answers for `ctx.apis` operations, typed by the spec: the value, or a `Response` decoded like the API's
   * (`() => Response.json({ message: "Not Found" }, { status: 404 })` for a typed error). Others go to `fetch`:
   * `apis: { github: { issuesListForRepo: ({ repo }) => [{ number: 1, title: "Bug", state: "open" }] } }`.
   */
  readonly apis?: ApiStubs<AppApisOf<T>>
  /**
   * Who is in the organization, for `org` and `private` apps (on the platform it lists them). Without it, those
   * apps let in every signed-in test user. `access: { emails: ["ana@example.com"], domains: ["acme.com"] }`.
   */
  readonly access?: { readonly emails?: ReadonlyArray<string>; readonly domains?: ReadonlyArray<string> }
  /**
   * Resizes images for sized links (`files.url(id, { size })`). Default: `fakeResizer()` (6 bytes of "WEBP" and the
   * width, as `image/webp`; "not an image" unless the bytes start like a PNG, JPEG, GIF or WebP). `false`: none, as on
   * the dev server (the original is served).
   */
  readonly resizeImage?: ImageResizer | false
}

SeedContext interfacesrc/testing/index.ts

interface SeedContext<T extends AnyApp> {
  /** A user. `as("viewer")` is the user the storyboard browses as; any other name is another person. */
  as(name: string): TestUser<T>
  /**
   * Run an internal mutation (`app({ internal })`) as `canica run` does (the system user), for data no page can make:
   * `run("savePreview", { link, title: "Dune", poster })`. Returns its value; throws when it fails.
   */
  run<N extends (keyof T["internal"] | keyof T["mutations"]) & string>(name: N, args?: unknown): unknown
  /** The seed's clock (epoch ms). Starts at the engine's time (the storyboard's fixed time, 2026-01-15 12:00 UTC unless the seed sets `now`); `setTime(now() - 7 * DAY)` to create history, then `advance`. */
  readonly now: () => number
  /**
   * A small sample photo (PNG) to upload, so image fields have something to show:
   * `const image = await as("viewer").uploadOk(sampleImage(), "photo.png")` (the seed function is `async`).
   */
  sampleImage(): Blob
  /** Move the clock forward (ms). `advance(DAY)` between check-ins, `advance(5 * MINUTE)` between messages. */
  advance(ms: number): void
  /** Set the clock (epoch ms), also into the past. It never goes past that starting time. */
  setTime(ms: number): void
  /**
   * A calendar day `"YYYY-MM-DD"` relative to today (the starting time) (local time): `day(0)` is today,
   * `day(-1)` yesterday. Use it for `day()` fields the UI compares with `useToday()`.
   */
  day(offset: number): string
  /**
   * Set the clock to a local time of day relative to today: `at(-1, "09:30")` is yesterday at 9:30,
   * `at(0, "08:05")` this morning. Use it so seeded times match the text ("Morning everyone" at 9:30).
   */
  at(dayOffset: number, time: string): void
}

SeedCaptures typesrc/testing/index.ts

Optionally returned by a seed: which params the storyboard captures per route, instead of the first and last row. { "/polls/$poll": [{ poll: mine }, { poll: closed }, { poll: someoneElses }] }.

type SeedCaptures = Readonly<Record<string, ReadonlyArray<Readonly<Record<string, string | number>>>>>

Seed typesrc/testing/index.ts

A seed may be async (await as("viewer").uploadOk(sampleImage())).

type Seed<T extends AnyApp> = ((ctx: SeedContext<T>) => SeedResult | Promise<SeedResult>) & { readonly "~now"?: number }

SeedOptions interfacesrc/testing/index.ts

interface SeedOptions {
  /**
   * The storyboard's "now" (epoch ms or an ISO date): seeded data and every screen are at this time. Default
   * 2026-01-15 12:00 UTC.
   */
  readonly now?: number | string
}

ImageResizer typesrc/core/files.ts

Resizes an image to width (never wider than it is), as WebP; "not an image" when the bytes cannot be read as one (that is final: the original is served from then on). Throws when it could not resize now (try again later). Production: Cloudflare's Images binding (imagesResizer in canica/cloudflare). Tests: fakeResizer().

type ImageResizer = (bytes: Uint8Array, options: { readonly width: ImageWidth; readonly type: string }) => Promise<{ readonly bytes: Uint8Array; readonly type: string } | "not an image">

Step typesrc/testing/scene.ts

type Step =
| { readonly step: "as"; readonly name: string; readonly signedIn?: boolean | TestProfile }
| { readonly step: "visit"; readonly path: string; readonly params?: Lazy<Record<string, unknown>> }
| { readonly step: "click"; readonly target: Locator }
| { readonly step: "type"; readonly target: Locator; readonly text: Lazy<string> }
| { readonly step: "choose"; readonly target: Locator; readonly option: Lazy<string> }
| { readonly step: "upload"; readonly target: Locator; readonly file: Lazy<File> }
| { readonly step: "see"; readonly target: Locator; readonly count?: number }
| { readonly step: "notSee"; readonly target: Locator }
| { readonly step: "meanwhile"; readonly run: () => unknown }
| { readonly step: "within"; readonly target: Locator; readonly steps: ReadonlyArray<Step> }

Locator typesrc/testing/scene.ts

type Locator =
| { readonly by: "role"; readonly role: string; readonly options?: RoleOptions }
| { readonly by: "label" | "text" | "placeholder"; readonly text: Lazy<string | RegExp> }

Id typesrc/server/fields.ts

A row id tagged with its table. Id<"todos"> is not assignable to Id<"users">.

type Id<Table extends string> = string & { readonly [IdBrand]: Table }

UserId typesrc/server/fields.ts

A Canica user reference (guest or signed in).

type UserId = string & { readonly [UserIdBrand]: "UserId" }