# Testing

This page is the test file the template ships, the three cases every workflow carries, once more over `checkout.complete`, and the proof that crashes a run at every boundary. The commands it teaches are `pnpm test` (the template's `vitest run`), `durable-sdk test --changed`, `durable-sdk test --pr` and `durable-sdk test store --url <postgres url>`.

A workflow test is one import and the harness: `testDurable()` of `@durable-sdk/testing` binds the engine to your `durable.config.ts` over in-memory stores with a clock the test moves, and its readers answer what the console would show. No database, seconds per file.

## The harness

```ts
import { testDurable } from "@durable-sdk/testing";

const t = testDurable({
  clock: { start: "2026-10-28T12:00:00Z" },
  tickTasks: [],
});
```

- `t.run(definition, input, { actor? })` executes as `system:test` and answers `execute`'s value.
- `t.detail(runId)`, `t.steps(runId)`, `t.ledger(scope?)`, `t.outbox(filter?)`, `t.waits()` read the rows.
- `t.emit(name, payload)` queues a fact as a route would; `t.tick()` is one whole dispatch tick.
- `t.advance("3h")` moves the clock a tick a minute: a timer, a slot and a delayed fact fire when due, never early.
- `t.crashAfterStep(seq, { workflow })`, `t.crashBeforeFinish(true, { workflow })` and `t.crashInsideStep(seq, { after: "write", workflow })` arm one crash; `t.crashed()` says where it fired.
- `t.logged()` returns the engine's lines under `logs: "collect"`; `t.dispose()` closes the harness.

The clock is the harness's: a body reads a moment from a step, never `Date.now()`, and `advance` is the only way time moves. A retry's delay and a provider bucket's refill go through the same clock, so a test of a retried step advances through each wait instead of waiting it.

## `tests/hello.test.ts`

The template ships this one file over its `hello.say` workflow with the three cases every workflow carries: the same intent twice is one run and the fact lands once; a failing step leaves the run `FAILED` as a value, nothing to undo, until a redrive; crashed after its step and claimed by the resumer, the run completes on attempt 2 with the effect applied once.

```ts
/**
 * `hello.say` on the test harness (`testDurable`: memory stores, a clock
 * the test moves, the engine's own tick): the same intent twice is one
 * run and the fact lands once; a failing step leaves the run FAILED as a
 * value until a redrive; crashed after its step, the run resumes on
 * attempt 2 with the step served from attempt 1's row.
 */
import { testDurable } from "@durable-sdk/testing";
import { afterEach, describe, expect, it } from "vitest";

import { HOST_EVENTS } from "../src/events/catalog.js";
import { helloEffects, helloSay } from "../src/workflows/hello.js";

const T0 = "2026-09-28T12:00:00.000Z";
const harnesses: ReturnType<typeof testDurable>[] = [];
/** A harness at T0 over this app's catalog and the engine's own tick: the lanes and the resumer, no host task. */
function open() {
  const t = testDurable({
    clock: { start: T0 },
    tickTasks: [],
    catalog: HOST_EVENTS,
  });
  harnesses.push(t);
  return t;
}
afterEach(async () => {
  for (const t of harnesses.splice(0)) await t.dispose();
});

/** The effects as a double: `greet` answers a receipt or refuses as told, `forget` records what it was handed; every call counted. */
function bind(refuse: string | null = null) {
  const calls = { greet: 0, forget: [] as string[] };
  Object.assign(helloEffects, {
    greet: async () => {
      calls.greet += 1;
      if (refuse !== null) throw new Error(refuse);
      return { receipt: `rcpt-${calls.greet}` };
    },
    forget: async (receipt: string) => {
      calls.forget.push(receipt);
    },
  });
  return calls;
}

describe("hello.say", () => {
  it("the same intent twice is one run: the second start answers the first, the effect applied once, one ledger row, the fact emitted once; another request is another run", async () => {
    const calls = bind();
    const t = open();
    const input = { name: "world", requestId: "q1" };
    const first = await t.run(helloSay, input);
    expect(first).toMatchObject({
      status: "completed",
      output: { receipt: "rcpt-1" },
    });
    const again = await t.run(helloSay, input);
    expect(again).toMatchObject({
      status: "completed",
      reused: true,
      runId: first.runId,
    });
    expect(calls.greet).toBe(1);
    expect(await t.ledger()).toMatchObject([
      {
        runId: first.runId,
        step: "hello.say.greet",
        after: { receipt: "rcpt-1" },
      },
    ]);
    expect(await t.outbox({ name: "hello.said" })).toMatchObject([
      { name: "hello.said", payload: { name: "world", requestId: "q1" } },
    ]);
    const other = await t.run(helloSay, { name: "world", requestId: "q2" });
    expect(other.runId).not.toBe(first.runId);
  });

  it("a failing step leaves the run FAILED as a value with nothing to undo, the undo never called, and the same intent answers the same run until a redrive", async () => {
    const calls = bind("the provider said no");
    const t = open();
    const input = { name: "nobody", requestId: "q1" };
    const r = await t.run(helloSay, input);
    expect(r).toMatchObject({
      status: "failed",
      error: "the provider said no",
    });
    expect((await t.detail(r.runId))!).toMatchObject({
      status: "FAILED",
      compensation: { undone: [], irreversible: [], failed: [] },
    });
    expect(calls.forget).toEqual([]);
    expect(await t.run(helloSay, input)).toMatchObject({
      status: "failed",
      reused: true,
      runId: r.runId,
    });
    expect(calls.greet).toBe(1);
  });

  it("crashed after its step and claimed by the resumer, the run completes on attempt 2 with the step served from attempt 1's row: the effect applied once, one ledger row", async () => {
    const calls = bind();
    const t = open();
    t.crashAfterStep(1, { workflow: "hello.say" });
    const crashed = await t.run(helloSay, { name: "again", requestId: "q1" });
    expect(crashed).toMatchObject({ status: "in_progress", fenced: true });
    await t.advance(t.durable.leaseMs + 60_000);
    const detail = (await t.detail(crashed.runId))!;
    expect(detail).toMatchObject({
      status: "COMPLETED",
      attempts: 2,
      output: { receipt: "rcpt-1" },
    });
    expect(detail.steps.map((s) => [s.attempt, s.name, s.status])).toEqual([
      [1, "hello.say.greet", "COMPLETED"],
    ]);
    expect(calls.greet).toBe(1);
    expect(await t.ledger()).toHaveLength(1);
  });
});
```

The effects seam is what makes the double cheap: the test binds `greet` and `forget` as counters and the workflow never knows. A connector you own is the same shape, a fake with `calls`, `answer`, `fail` and `failAfter` ("applied, then the answer was lost") so a redrive after a lost answer is proved to adopt the write and never make it twice.

## `tests/checkout-complete.test.ts`

The same three cases over `checkout.complete` once the file of [Writing a workflow](https://durablesdk.com/docs/guide/writing-a-workflow.md) has `payment.capture` and `order.create` after `stock.reserve`, each over the seam (`capture` and `refund`, `create` and `cancel` beside `reserve` and `release`), and emits `order.placed`. The whole run leaves three ledger rows and the fact once; the same intent twice is one run and every provider is called once; the last step throwing runs the two undos in reverse and lands the run `COMPENSATED`, the fact never written.

```ts
import { testDurable } from "@durable-sdk/testing";
import { afterEach, describe, expect, it } from "vitest";

import { HOST_EVENTS } from "../src/events/catalog.js";
import {
  checkoutComplete,
  checkoutCompleteEffects,
} from "../src/workflows/checkout-complete.js";

const harnesses: ReturnType<typeof testDurable>[] = [];
function open() {
  const t = testDurable({
    clock: { start: "2026-10-29T09:14:02.000Z" },
    tickTasks: [],
    catalog: HOST_EVENTS,
  });
  harnesses.push(t);
  return t;
}
afterEach(async () => {
  for (const t of harnesses.splice(0)) await t.dispose();
});

/** The seam as doubles: each provider call counted, the order's create refusing as told, each undo recording what it was handed. */
function bind(refuse: string | null = null) {
  const calls = { reserve: 0, capture: 0, create: 0, undone: [] as string[] };
  Object.assign(checkoutCompleteEffects, {
    reserve: async () => {
      calls.reserve += 1;
      return { reservationId: "res_12", stock: 2 };
    },
    release: async (reservationId: string) => {
      calls.undone.push(`release ${reservationId}`);
    },
    capture: async () => {
      calls.capture += 1;
      return { paymentId: "pay_7f3a", amount: 4200 };
    },
    refund: async (paymentId: string) => {
      calls.undone.push(`refund ${paymentId}`);
    },
    create: async () => {
      calls.create += 1;
      if (refuse !== null) throw new Error(refuse);
      return { orderId: "ord_8841" };
    },
    cancel: async (orderId: string) => {
      calls.undone.push(`cancel ${orderId}`);
    },
  });
  return calls;
}

describe("checkout.complete", () => {
  it("the whole run: three steps, three ledger rows, the fact once", async () => {
    const calls = bind();
    const t = open();
    const r = await t.run(checkoutComplete, {
      checkoutId: "chk_4f21",
      requestId: "q7c1",
    });
    expect(r).toMatchObject({
      status: "completed",
      output: { orderId: "ord_8841" },
    });
    expect((await t.ledger()).map((row) => row.step)).toEqual([
      "stock.reserve",
      "payment.capture",
      "order.create",
    ]);
    expect(await t.outbox({ name: "order.placed" })).toMatchObject([
      {
        payload: {
          orderId: "ord_8841",
          checkoutId: "chk_4f21",
          requestId: "q7c1",
        },
      },
    ]);
    expect(calls.undone).toEqual([]);
  });

  it("the same intent twice is one run: the second start answers the first, every provider called once", async () => {
    const calls = bind();
    const t = open();
    const input = { checkoutId: "chk_4f21", requestId: "q7c1" };
    const first = await t.run(checkoutComplete, input);
    const again = await t.run(checkoutComplete, input);
    expect(again).toMatchObject({
      status: "completed",
      reused: true,
      runId: first.runId,
    });
    expect([calls.reserve, calls.capture, calls.create]).toEqual([1, 1, 1]);
    expect(await t.outbox({ name: "order.placed" })).toHaveLength(1);
  });

  it("the last step throwing: the undos run in reverse, the run lands COMPENSATED, the fact never written", async () => {
    const calls = bind("tax: 503 Service Unavailable");
    const t = open();
    const r = await t.run(checkoutComplete, {
      checkoutId: "chk_4f22",
      requestId: "q7c1",
    });
    expect(r).toMatchObject({
      status: "compensated",
      error: "tax: 503 Service Unavailable",
    });
    expect((await t.detail(r.runId))!).toMatchObject({
      status: "COMPENSATED",
      compensation: {
        undone: ["payment.capture", "stock.reserve"],
        irreversible: [],
        failed: [],
      },
    });
    expect(calls.undone).toEqual(["refund pay_7f3a", "release res_12"]);
    expect(await t.outbox({ name: "order.placed" })).toEqual([]);
  });
});
```

The seam is why the doubles are cheap: the test binds six functions as counters and the workflow never knows; `calls.undone` is the order the saga ran the undos in, the capture refunded before the stock is released.

## `prove`: the double-run proof

`prove(definition, options)` runs the clean run first, then the same run crashed and resumed at every boundary the memory store offers: before each step's row, after it, inside each step that called a provider, and at the finish. It judges each: `COMPLETED` at attempt 2, every landed row served and nothing invoked twice, no memo lost to the cap or a secret, the fakes' provider counts per step equal to the clean run's. The answer is a `Proof` whose every finding is a sentence with its remedy.

```ts
import { prove, testDurable } from "@durable-sdk/testing";
import { expect, it } from "vitest";

import { checkoutComplete } from "../src/workflows/checkout-complete";

it("survives a crash at every boundary", async () => {
  const proof = await prove(checkoutComplete, {
    harness: () => testDurable({ tickTasks: [], logs: "collect" }),
    run: (t) =>
      t.run(checkoutComplete, { checkoutId: "chk_4f21", requestId: "q7c1" }),
  });
  expect(proof.ok).toBe(true);
});
```

Your workflow is in the proof the day it is registered: the template's guard runs it over every definition's `example`. A definition whose example needs rows carries them as its `world`.

## The commands

| Command                                               | What it runs                                                                                                                                                            |
| ----------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `pnpm test`                                           | `vitest run`: every file under `tests/`, the harness over memory stores                                                                                                 |
| `durable-sdk test --changed [--base <ref>]`           | The quick tier: the tests the change reaches and the guards it can break                                                                                                |
| `durable-sdk test --pr [--base <ref>] [--keep-going]` | The proving tier a pull request needs: every tier, the proof, the doctor; `--summary <file>` appends the verdict table                                                  |
| `durable-sdk test store --url <postgres url>`         | The store conformance suite against your own Postgres: the fences, the ledger trigger, the lease, the outbox                                                            |
| `durable-sdk platform check --api <url>`              | A deployment proved live: the doors answer, the cron ticks, the definitions key the same; the hosted deploy runs it before a promotion ([Deploy](https://durablesdk.com/docs/hosting/deploy.md)) |

`durable-sdk test --pr` is what the template's CI runs; its exit code is the verdict (0 green, 1 a red test or proof, 2 a bad flag).

## What never passes

A step body invoked twice across a crash, a provider write made again after a lost record, a memo lost to an output past the cap, a secret in an output, a key that reads the clock, a run body that reads the world between steps. Each is a finding with its remedy, never a flake. The engine's own four layers of testing (unit, store proof, tree rules, platform contract) are on the generated page [Testing](https://durablesdk.com/docs/testing.md).

---

Prompt for an agent:

```text
Read https://durablesdk.com/docs/guide/testing.md, then write the three tests every workflow carries and run the double-run proof on it; run durable-sdk doctor --host before and after; a refused line is a refusal id: durable-sdk explain <id>
```
