Skip to content

Testing

Story.run runs actor handlers on an in-memory test host. The host drives your handlers through the turn worker ABI, the same way akterd does. Each actor gets its own in-memory SQLite database, and every story starts empty. Commands, queries, timers, messages, and jobs all run on that host.

Each story is a standard Effect. Run a story directly with Effect.runPromise, or return it from it.effect in @effect/vitest.

Model a command that rolls back on error⁠

This Account actor keeps a balance in its Open state and records withdrawals in an audit table:

audit.table.ts
import { Schema } from "effect"
import { Akter } from "@akterjs/effect/contract"

export const AuditTable = Akter.table("audit", {
  columns: { amount: Schema.Int, id: Schema.String },
  indexes: [],
  primaryKey: ["id"],
})
account.contract.ts
import { Schema } from "effect"
import { Akter } from "@akterjs/effect/contract"
import { AuditTable } from "./audit.table.ts"

export class InsufficientFundsError extends Schema.TaggedError<InsufficientFundsError, { readonly brand: unique symbol }>()(
  "InsufficientFundsError",
  {},
) {}

export const Owner = Akter.caller("user", Schema.Struct({ id: Akter.PrincipalId }))

export const Open = Schema.TaggedStruct("Open", { balance: Schema.Int })

export const Account = Akter.make("Account", {
  callers: [Owner],
  commands: {
    withdraw: Akter.command({
      callers: [Owner],
      errors: [InsufficientFundsError],
      from: [Open],
      input: Schema.Struct({ amount: Schema.Int }),
      output: Schema.Int,
      to: [Open],
    }),
  },
  initial: { input: Schema.Void, to: Open },
  key: Schema.String,
  parent: Akter.Root,
  queries: {
    auditRows: Akter.query({ callers: [Owner], errors: [], input: Schema.Void, output: Schema.Int, states: [Open] }),
    balance: Akter.query({ callers: [Owner], errors: [], input: Schema.Void, output: Schema.Int, states: [Open] }),
  },
  states: [Open],
  tables: [AuditTable],
})

The withdraw handler inserts into audit before it checks account.balance. InsufficientFundsError rolls back the audit row and the transition:

account.actor.ts
import { Effect } from "effect"
import { Akter } from "@akterjs/effect/contract"
import { Account, InsufficientFundsError, Open } from "./account.contract.ts"
import { AuditTable } from "./audit.table.ts"

export const AccountLive = Account.toLayer({
  commands: {
    withdraw: (account, { amount }) =>
      Effect.gen(function* () {
        const db = yield* Akter.db
        const id = yield* Akter.id
        yield* db.insert(AuditTable).values({ amount, id })
        if (amount > account.balance) {
          return yield* InsufficientFundsError.make({})
        }
        const next = Open.make({ balance: account.balance - amount })
        return { next, output: next.balance }
      }),
  },
  initial: () => ({ next: Open.make({ balance: 50 }) }),
  queries: {
    auditRows: () => Effect.flatMap(Akter.db, (db) => db.$count(AuditTable)),
    balance: (account) => Effect.succeed(account.balance),
  },
})

Verify rollback and isolation⁠

To get a typed actor client inside a story, call story.actor(Contract, key, { as }). After a failed command, query the stored state and the table’s row count to confirm that the rollback left no partial write:

account.story.ts
import assert from "node:assert/strict"
import { Effect } from "effect"
import { Akter } from "@akterjs/effect/contract"
import { Story } from "@akterjs/effect/testing"
import { Account, Owner } from "./account.contract.ts"
import { AccountLive } from "./account.actor.ts"

const owner = (id: string) => ({ caller: Owner, principal: { id: Akter.PrincipalId.make(id) } })

const program = Story.run(AccountLive, function* (story) {
  const ada = yield* story.actor(Account, "ada", { as: owner("ada") })
  const grace = yield* story.actor(Account, "grace", { as: owner("grace") })

  const refused = yield* Effect.flip(ada.withdraw({ amount: 80 }))
  assert.equal(refused._tag, "InsufficientFundsError")
  assert.equal(yield* ada.balance(), 50)
  assert.equal(yield* ada.auditRows(), 0)

  assert.equal(yield* ada.withdraw({ amount: 30 }), 20)
  assert.equal(yield* ada.balance(), 20)
  assert.equal(yield* ada.auditRows(), 1)
  assert.equal(yield* grace.balance(), 50)
  console.log("rollback, stored state and isolation passed")
})

Effect.runPromise(program)
Text
rollback, stored state and isolation passed

Effect.flip fails the test if withdraw succeeds when it should fail. Subsequent assertions verify that a valid withdrawal commits cleanly while leaving grace untouched.

Advance virtual time and drain background work⁠

Commands in a story automatically drain immediately due messages, timers, and jobs before returning. To trigger future timers and delayed retries without real sleeps, call story.advance("1 hour").

Story.run reuses an existing runner TestClock when present, and provides its own TestClock otherwise. See Timers and messages and Jobs for scheduled workflow tests.

Test caller principals and explicit creation⁠

Every story client names its caller. To call an actor as a specific principal, pass { as: { caller, principal } } to story.actor. caller is a value from the contract’s callers list, and principal matches that caller’s schema.

To create an actor whose initial.input is not Schema.Void, call story.create(Contract, key, { as, input }). A command or query with Schema.Void input takes no argument on a story client. Access and Actors show complete examples.

Replay a story under crash schedules⁠

To check that a story holds while its host crashes, call Story.chaos(target, { schedules, seed }, body). To replay it on the in-memory host, pass Story.inMemory(handlers) as the target. To replay it on akterd --local, pass storyTargetOf(akterdHostOf(binary)) from @akterjs/conformance. Jobs shows a complete example.

Story.chaos reference⁠

  • Target. A StoryTarget value names the host. Story.inMemory(handlers) builds the in-memory host. storyTargetOf(host) from @akterjs/conformance wraps a conformance HostOf, such as akterdHostOf(binary).
  • Schedules. Story.chaos first runs the body once with no crashes and counts the chaos points that the host reaches. It then runs the body once per chaos point, with a crash at that point. Last, it runs schedules seeded schedules with the seeds seed + 1 through seed + schedules.
  • Seeded crashes. A seeded schedule crashes at about one chaos point in five, and at most 3 times.
  • Chaos points. A job reaches a chaos point when its run starts, before and after each activity, and before, during and after each step. It also reaches one before and after its result lands. A file write reaches a chaos point before, during and after the write.
  • Crashes on each host. The in-memory host revives its jobs from their journals after a crash. akterd --local aborts at the chaos point. The akterd target then starts akterd again on the same data folder and retries the call that lost its connection.
  • Report. ChaosReport holds points, schedules and crashes. points counts the chaos points of the run with no crashes. schedules counts the crash schedules. crashes counts the crashes over all schedules. Both targets report the same shape.
  • Failures. A failed assertion, a defect or a typed error in any schedule fails the Story.chaos effect.

Story.chaos names its host with one value⁠

Story.chaos takes its host as a StoryTarget value, so one story body runs on every host through one signature. A string name or an optional host field would give the call a second form. The target owns how its host starts, counts chaos points and restarts after a crash. The story driver sees only commands, queries, creates, drain and advance.

The report counts crashes and does not name the chaos points. akterd reports only how many chaos points it reached and how many crashes it took. A report with point names would hold data that one host cannot give.

Story.run takes handlers and no target. A story with no crashes runs on the in-memory host.

What stories cover⁠

Story.run exercises SQLite transactions, handler logic, caller checks, timers, messages, jobs, and virtual time. It does not simulate host restarts, network partitions, or disk loss. Story.chaos adds host crashes at chaos points and restarts after them. The in-memory host never reopens stored state, so a story creates every declared table in an empty database. Changing tables and state covers what that means for table changes and state upgrades.