Previewkernable is not released yet: these docs describe work in progress, and things may change before 1.0.Not released yet.Request early access →
Skip to content

Test your domain ​

Aggregates are plain functions of events and commands (Decide and fold), so most of your domain can be tested without a kernel: fold past events into a state with the aggregate's fold, then call a command handler on that state and check the events it returns, or the rejection.

Aggregates, without a kernel ​

ts
/** Runs `type` on the state after `history`, as a worker would. */
function decide(history: { type: string; data?: unknown }[], type: string, data: unknown = {}) {
  const state = orderAggregate.fold(history.map((e) => ({ schema: 1, data: {}, ...e })));
  return orderAggregate.handle(state, type, data, new CommandContext("test", {}, new Date("2026-01-01T00:00:00Z")));
}

test("a draft order with items can be submitted", async () => {
  const placed = { type: "OrderPlaced", data: { customerId: "c1" } };
  const added = { type: "ItemAdded", data: { sku: "apple", qty: 2 } };
  assert.deepEqual(await decide([placed, added], "Submit"), [{ type: "OrderSubmitted" }]);
});

test("an empty order cannot be submitted", async () => {
  const placed = { type: "OrderPlaced", data: { customerId: "c1" } };
  await assert.rejects(async () => decide([placed], "Submit"), (err: Rejected) => err.code === "invalid_state");
});
py
def decide(history, type, data=None):
    """Runs `type` on the state after `history`, as a worker would."""
    state = order_aggregate.fold([(e["type"], 1, e.get("data", {})) for e in history])
    at = datetime(2026, 1, 1, tzinfo=timezone.utc)
    return order_aggregate.handle(state, type, data, CommandContext.new("test", received_at=at))


class OrderTest(unittest.TestCase):
    placed = {"type": "OrderPlaced", "data": {"customerId": "c1"}}

    def test_a_draft_order_with_items_can_be_submitted(self):
        added = {"type": "ItemAdded", "data": {"sku": "apple", "qty": 2}}
        self.assertEqual(decide([self.placed, added], "Submit"), [{"type": "OrderSubmitted"}])

    def test_an_empty_order_cannot_be_submitted(self):
        with self.assertRaises(Rejected) as rejected:
            decide([self.placed], "Submit")
        self.assertEqual(rejected.exception.code, "invalid_state")
rs
/// Runs `command_type` on the state after `history`, as a worker would.
fn decide(history: &[(&str, Value)], command_type: &str) -> Result<Vec<NewEvent>, Error> {
    let order_aggregate = shop::shop().order_aggregate;
    let state = order_aggregate.fold(
        history.iter().map(|(t, data)| FoldEvent::new(t, data)),
        None,
    )?;
    let mut ctx = CommandContext::new(
        "test",
        RequestContext::default(),
        Timestamp(1_767_225_600_000),
    );
    order_aggregate.handle(&state, command_type, (), &mut ctx)
}

#[test]
fn a_draft_order_with_items_can_be_submitted() {
    let placed = ("OrderPlaced", json!({ "customerId": "c1" }));
    let added = ("ItemAdded", json!({ "sku": "apple", "qty": 2 }));
    assert_eq!(
        decide(&[placed, added], "Submit").unwrap(),
        [NewEvent::new("OrderSubmitted", ())]
    );
}

#[test]
fn an_empty_order_cannot_be_submitted() {
    let placed = ("OrderPlaced", json!({ "customerId": "c1" }));
    assert!(
        matches!(decide(&[placed], "Submit"), Err(Error::Rejected(r)) if r.code == "invalid_state")
    );
}

These run with node --test, python -m unittest and cargo test. They test the tutorial's order aggregate.

  • Given is the history you fold: events as { type, schema, data } in TypeScript, (type, schema, data) tuples in Python, FoldEvent::new(type, data) in Rust (schema 1).
  • When is the handler you call, with a fixed clock and fixed IDs in the context, so the result is the same on every run.
  • Then is the list of new events, or a Rejected with its code.

fold upcasts every event first, as a worker does. To test an upcast (Change an event's format), fold an event at its old schema, such as { type: "ItemAdded", schema: 1, data: { sku: "apple", qty: 2 } }, and check the state.

To test unique keys and facts, pass a folded state to the aggregate's index: it returns the keys and facts a worker would send for it (Unique keys and conditions).

Read models, reactors and middleware, against a real kernel ​

These depend on the kernel: order, settling, queries and checks. Test them end to end:

  1. Start a kernel that keeps nothing, in a temporary directory:

    sh
    cd "$(mktemp -d)"
    kernable start --dev --store memory: --listen 127.0.0.1:17233 --metrics-listen 127.0.0.1:17234

    --dev creates the keys there, among them app.key with a grant that may do everything.

  2. Start your processes against it, with KERNABLE_URL=http://127.0.0.1:17233 and KERNABLE_KEY=<that directory>/app.key.

  3. Wait until they are connected: await app.ready in TypeScript, app.ready.wait(5) in Python, .ready().await in Rust. Do not sleep.

  4. Send commands and queries as your API would. A submit settles by default, so the next query already sees its events.

Do not rely on /ready alone to wait for your processes: before they connect for the first time, the kernel does not know them, unless their service's membership was applied.

To see how kernable sets this up for its own tests, look at sdks/typescript/test/kernel.ts, sdks/python/tests/kernel.py and sdks/rust/tests/common/mod.rs in the repository. These helpers are not part of the SDKs.