<!-- https://tinyactors.dev/guides/testing-recipes/ -->
# Testing recipes

Kind: how-to. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).

> Examples for testing chart timeouts, retries, and service replies with Tiny Actors.

Test retries and timeouts with a clock you control and handlers that answer when the test needs them to.

<a id="websocket-test"></a>

## Test a WebSocket reconnect

This case drops the connection, advances to the next timer, and reports a successful reply. It checks that the chart reconnects and clears its timers.

```javascript title="main.mjs"
lab.drop();
const waiting = await lab.read();
assert.deepEqual(waiting.timers.map(timer => timer.due), [2000, 30000]);
await lab.advance(waiting.timers[0]);
assert.equal((await lab.read()).pending, 1);
lab.reply(true);
const reopened = await lab.read();
assert.equal(reopened.value, 'online');
assert.deepEqual(reopened.timers, []);
```

[Try the WebSocket reconnect lab](https://tinyactors.dev/guides/testing/index.md#reconnect-lab).

<a id="three-tools"></a>

## Replace the chart's services and its clock

A chart reaches the world only through sends. The host passes each send to a handler you give it, an I/O processor.

- **The test's handlers stand in for the services.**: They record what the chart sent and answer when the case needs it, with an error, or never.
- **A `SimulatedClock` moves only when the test moves it.**: A timeout of an hour takes no time.
- **`await host.idle()` returns when the host has nothing left to do.**: Assertions after it see everything the inputs before it did by the clock's time.

To check properties over generated runs instead of single cases, read [Property testing a statechart](https://tinyactors.dev/property-testing/index.md).

<a id="a-test"></a>

## Check each step of a retrying payment

This chart charges a card, retries when no answer comes within 30 seconds, and gives up after the third attempt. Its test moves the clock 30 seconds at a time and checks each charge.

```javascript title="payment.test.mjs"
import assert from 'node:assert/strict';
import { compileCharts, Host, SimulatedClock, StaleError } from '@tinyactors/node';

const chart = `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="payment" initial="charging">
  <datamodel><data id="attempts" expr="0"/></datamodel>
  <state id="charging">
    <onentry>
      <assign location="attempts" expr="attempts + 1"/>
      <send type="urn:example:payments" event="charge" target="card"/>
      <send event="timeout" delay="30s" id="timer"/>
    </onentry>
    <transition event="charged" target="paid"><cancel sendid="timer"/></transition>
    <transition event="timeout" cond="attempts &lt; 3" target="charging"/>
    <transition event="timeout" target="failed"/>
  </state>
  <final id="paid"/>
  <final id="failed"><onentry><log label="payment" expr="'gave up after ' + attempts"/></onentry></final>
</scxml>`;

/** A host running the chart on a simulated clock, recording its charges. */
function setup() {
  const compiled = compileCharts([{ name: 'payment.scxml', text: chart }]);
  const clock = new SimulatedClock();
  const charges = [];
  const logs = [];
  const host = new Host(compiled, {
    system: 'test',
    clock,
    ioProcessors: { 'urn:example:payments': { receive: (send) => charges.push({ at: clock.now, target: send.target }) } },
    log: (entry) => logs.push(entry.text),
  });
  compiled.close();
  return { host, clock, charges, logs };
}

/** The actor's state value, read with a typed method. */
const state = async (actor) => (await actor.state()).value;

// It retries every 30 seconds and gives up after three attempts.
{
  const { host, clock, charges, logs } = setup();
  const payment = host.spawn('payment', { name: 'payment' });
  await host.idle();
  assert.deepEqual(charges, [{ at: 0, target: 'card' }]);
  assert.equal(await state(payment), 'charging');

  clock.increment(30_000);
  await host.idle();
  clock.increment(30_000);
  await host.idle();
  assert.deepEqual(charges.map((charge) => charge.at), [0, 30_000, 60_000]);

  clock.increment(30_000);
  await host.idle();
  assert.deepEqual(logs, ['gave up after 3']);
  assert.throws(() => host.actor('payment'), StaleError, 'a final state ends the actor');
  host.close();
  console.log('ok: retries, then gives up');
}

// An answer before the timeout ends it, and no timer is left.
{
  const { host, clock, charges } = setup();
  const payment = host.spawn('payment', { name: 'payment' });
  await host.idle();
  payment.send('charged');
  await host.idle();
  assert.throws(() => host.actor('payment'), StaleError);
  assert.equal(host.nextDeadline, undefined, 'the timer was cancelled');
  clock.increment(60_000);
  await host.idle();
  assert.equal(charges.length, 1);
  host.close();
  console.log('ok: an answer ends it');
}
```

```text title="output"
ok: retries, then gives up
ok: an answer ends it
```

The second case answers with `payment.send('charged')`, as the handler's `send.answer('charged')` would, without the `sendid`. A handler may answer just as well.

Read the actor's state with `actor.state()` after an `idle()`: it reads the host as it is when called ([Inspecting a host](https://tinyactors.dev/guides/inspection/index.md)).

Give the actor a name to see it end: a final state frees the name, so `host.actor(name)` throws `StaleError`.

<a id="stepping-the-clock"></a>

## Step to each deadline to see every tick

`clock.increment(ms)` moves the clock once. What is due by then runs once, at the new time, and a delay it starts counts from there.

So a chart that ticks every second ticks once for an `increment(3500)`, and its next tick is due a second later. Stepping by `host.nextDeadline`, the milliseconds to the next deadline, logs every tick:

```javascript title="ticker.mjs"
import { compileCharts, Host, SimulatedClock } from '@tinyactors/node';

const compiled = compileCharts([{ name: 'ticker.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="ticker" initial="ticking">
  <datamodel><data id="n" expr="0"/></datamodel>
  <state id="ticking">
    <onentry><send event="tick" delay="1s"/></onentry>
    <transition event="tick" target="ticking"><assign location="n" expr="n + 1"/><log expr="'tick ' + n"/></transition>
  </state>
</scxml>` }]);
const clock = new SimulatedClock();
const host = new Host(compiled, { system: 'test', clock, log: (entry) => console.log(entry.text, 'at', clock.now) });
compiled.close();
host.spawn('ticker');
await host.idle();

clock.increment(3500);             // one jump: one tick
await host.idle();
while (clock.now < 6500) {         // step deadline by deadline
  clock.increment(host.nextDeadline);
  await host.idle();
}
host.close();
```

```text title="output"
tick 1 at 3500
tick 2 at 4500
tick 3 at 5500
tick 4 at 6500
```

<a id="inputs-run-at-the-next-turn"></a>

## Await idle before you move the clock

`actor.send` returns before the actor handles the event, which it does later, at the clock's time then. Until then `host.nextDeadline` holds no deadline the event starts.

So an event sent just before an `increment` runs after the clock moved, and a delay it starts counts from there:

```javascript title="hold.mjs"
import { compileCharts, Host, SimulatedClock } from '@tinyactors/node';

const compiled = compileCharts([{ name: 'hold.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="hold" initial="s">
  <state id="s">
    <transition event="reserve"><log expr="'reserved'"/><send event="expire" delay="60s"/></transition>
    <transition event="expire"><log expr="'expired'"/></transition>
  </state>
</scxml>` }]);
const clock = new SimulatedClock();
const host = new Host(compiled, { system: 'test', clock, log: (entry) => console.log(entry.text, 'at', clock.now) });
compiled.close();
const actor = host.spawn('hold');
await host.idle();

actor.send('reserve');
console.log('nextDeadline right after the input:', host.nextDeadline);
clock.increment(59_000);          // the input runs now, at 59000: the hold is due at 119000
await host.idle();

actor.send('reserve');
await host.idle();                // the input runs at 59000, before the step
clock.increment(60_000);
await host.idle();
host.close();
```

```text title="output"
nextDeadline right after the input: undefined
reserved at 59000
reserved at 59000
expired at 119000
expired at 119000
```

Both holds came due at 119000, though the first was sent at 0. Await `idle()` after each event whose effect the next step or assertion needs.

<a id="waiting-for-something-to-happen"></a>

## On the real clock, await the actor's result

On the real clock, `await host.idle()` returns while a timeout is still pending. It waits only for work due now and for promises your handlers returned.

`await actor.done` waits instead for the actor's top-level final state, and settles with its `<donedata>`. `await actor.ask(event, data)` sends an event and settles with the chart's reply:

```javascript title="job.mjs"
import { compileCharts, Host } from '@tinyactors/node';

const compiled = compileCharts([{ name: 'job.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="job" initial="working">
  <datamodel><data id="progress" expr="0"/></datamodel>
  <state id="working"><onentry><send event="finish" delay="50ms"/></onentry>
    <transition event="how"><send event="progress" targetexpr="_event.origin"><content expr="progress"/></send></transition>
    <transition event="finish" target="done"/>
  </state>
  <final id="done"><donedata><content expr="'all done'"/></donedata></final>
</scxml>` }]);
const host = new Host(compiled, { system: 'test' });
compiled.close();

const job = host.spawn('job');
const [event, data] = await job.ask('how');
console.log('asked:', event, data);
await host.idle();
console.log('after idle():', (await host.actors()).length === 0 ? 'ended' : 'still running');
console.log('done:', await job.done);
host.close();
```

```text title="output"
asked: progress 0
after idle(): still running
done: all done
```

`ask` gives the event an origin the host answers itself. The chart replies with `<send targetexpr="_event.origin">`, as to another actor, and the promise settles with the reply's event name and data.

To give up on an ask, pass an `AbortSignal` as `ask(event, data, { signal })`. The ask rejects with the signal's reason, and a later reply is dropped.

A host closed while an ask waits leaves it pending for ever, as it leaves the promise of `actor.state()`.

<a id="until"></a>

## Wait until any condition holds

This helper checks a condition every 10 ms of the real clock and awaits `host.idle()` between checks. Here it waits for a lamp to be lit:

```javascript title="lamp.mjs"
import { compileCharts, Host } from '@tinyactors/node';

/** Turns the host until `condition()` holds, checking every 10 ms. */
async function until(host, condition, ms = 5000) {
  for (const end = Date.now() + ms; !(await condition()); ) {
    if (Date.now() > end) throw new Error('timed out');
    await new Promise((resolve) => setTimeout(resolve, 10));
    await host.idle();
  }
}

const compiled = compileCharts([{ name: 'lamp.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="lamp" initial="warming">
  <state id="warming"><onentry><send event="warm" delay="50ms"/></onentry>
    <transition event="warm" target="lit"/>
  </state>
  <state id="lit"/>
</scxml>` }]);
const host = new Host(compiled, { system: 'test' });
compiled.close();

const lamp = host.spawn('lamp');
await until(host, async () => (await lamp.state()).value === 'lit');
console.log('lit');
host.close();
```

```text title="output"
lit
```

<a id="prepared-world"></a>

## Start each test from a snapshot

Set up a host once and take `host.snapshot()`. Each test then starts with `Host.restore` of it, the same actors in the same states ([Snapshots](https://tinyactors.dev/guides/snapshots/index.md)).

<a id="both-datamodels"></a>

## Run the tests in QuickJS too

When production runs your charts in QuickJS, run each test a second time with `datamodel: 'quickjs'` on the host ([The quickjs sandbox](https://tinyactors.dev/guides/quickjs/index.md)).

<a id="habits-that-help"></a>

## Fail the test on a handler's error

A handler that throws makes the next `await host.idle()` reject, which fails the test ([Errors](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#errors)).

A host given `onHandlerError` reports the error there instead. Collect what it receives and assert the list is empty.

<a id="close-every-host"></a>

## Close every host in teardown

Call `host.close()` in a `finally` or the test framework's teardown. A forgotten host on a `SimulatedClock` lets the process exit, but holds its memory until collected.
