<!-- https://tinyactors.dev/property-testing/ -->
# Property testing a statechart

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

> Replace unit tests with properties: generate worlds from seeds, find the run that breaks the chart, shrink it, and read its trace. In your browser.

A unit test checks one run you thought of. A property holds for every run. Generate the runs, find the one that breaks, and shrink it. Everything on this page runs in your browser.

- Browsers: `npm install @tinyactors/wasm` (@tinyactors/wasm 0.4.0, 19 November 2026 · [What changed](https://tinyactors.dev/changelog/index.md#wasm-0-4-0) · [Browsers guide](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/docs/guide/browser.md))
- Node.js and Bun: `npm install @tinyactors/node` (@tinyactors/node 0.4.0, 19 November 2026 · [What changed](https://tinyactors.dev/changelog/index.md#node-0-4-0) · [Node.js and Bun guide](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/docs/guide/testing.md))

[Start](https://tinyactors.dev/property-testing/index.md#chart) · [Get the code](https://github.com/tinyactors-dev/tinyactors/tree/main/website/examples/property)

<a id="chart"></a>

## 1. Write the chart

A payment charges a card, retries after 30 seconds of silence, and gives up after three attempts.

```scxml title="payment.scxml"
<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:payments" event="charge" target="card">
        <param name="attempt" expr="attempts"/>
      </send>
      <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"><donedata><param name="outcome" expr="'paid'"/></donedata></final>
  <final id="failed"><donedata><param name="outcome" expr="'failed'"/></donedata></final>
</scxml>
```

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

## 2. Make the world data

The chart only sees events. So a world is an array: does the service answer charge 1, charge 2, and so on.

```javascript title="property.mjs"
// A run: the chart against a world. The world is data: answers[n] says
// whether the payment service answers the chart's charge number n. Nothing
// else decides what happens, so the same answers make the same run.
export async function run(compiled, answers, { trace = false } = {}) {
  const clock = new SimulatedClock();
  const charges = [];
  const requests = [];
  let outcome;
  const host = new Host(compiled, {
    system: 'property',
    clock,
    config: { system: { ticksPerSecond: 1000 }, ...(trace ? { telemetry: { resource: { 'service.name': 'payment' } } } : {}) },
    ...(trace ? { telemetry: (signal, data) => signal === 'traces' && requests.push(data) } : {}),
    ioProcessors: {
      'urn:payments': {
        receive(send) {
          const n = charges.push(clock.now) - 1;
          if (answers[n]) send.answer('charged');
        },
      },
    },
    onDone: (actor, donedata) => { outcome = donedata.outcome; },
  });
  host.spawn('payment');
  await host.idle();
  while (outcome === undefined) {
    clock.increment(host.nextDeadline); // the next timeout, at once
    await host.idle();
  }
  host.close(); // the last traces go to the telemetry handler here
  return { answers, charges, outcome, spans: requests.flatMap((data) => decodeTraces(data)) };
}
```

Run `[silence, answer]` with tracing on. Select a row to see its transitions.

[Run it](https://tinyactors.dev/property-testing/#world) · [live.mjs](https://tinyactors.dev/examples/property/live.mjs)

<a id="properties"></a>

## 3. State the properties

Whatever the service does, the payment charges at most three times and gives up only after the third charge. It is paid only when the service answered.

```javascript title="property.mjs"
// Properties: what must hold for every run, whatever the world did.
export const properties = {
  'never more than three charges': (r) => r.charges.length <= 3,
  'gives up only after three charges': (r) => r.outcome === 'paid' || r.charges.length === 3,
  'paid only when the service answered': (r) => r.outcome === 'failed' || r.answers.slice(0, r.charges.length).some(Boolean),
};

export const broken = (r) => Object.keys(properties).filter((name) => !properties[name](r));
```

<a id="search"></a>

## 4. Search a thousand worlds

A seed makes a world. The search runs seeds until one breaks a property, and the seed reproduces it.

```javascript title="property.mjs"
// A generator: a world from a seed, three to eight answers, each yes with
// probability 0.4. The seed reproduces it.
export function generate(seed) {
  const random = mulberry32(seed);
  return Array.from({ length: 3 + Math.floor(random() * 6) }, () => random() < 0.4);
}

// The search: worlds from seeds 1 to `seeds`, until one breaks a property.
export async function search(compiled, seeds) {
  for (let seed = 1; seed <= seeds; seed++) {
    const r = await run(compiled, generate(seed));
    if (broken(r).length) return { seed, run: r };
  }
  return null;
}
```

[Search](https://tinyactors.dev/property-testing/#search) · [live.mjs](https://tinyactors.dev/examples/property/live.mjs)

<a id="bug"></a>

## 5. Plant a bug

Retry while `attempts < 4`. A unit test that answers the first charge still passes.

```javascript title="main.mjs"
const buggy = compile(chart.replace('attempts &lt; 3', 'attempts &lt; 4')); // one retry too many
const failure = await search(buggy, 1000);
console.log(`seed ${failure.seed}: ${show(failure.run.answers)} breaks ${broken(failure.run).join(', ')}`);
```

[Search](https://tinyactors.dev/property-testing/#bug) · [live.mjs](https://tinyactors.dev/examples/property/live.mjs)

<a id="shrink"></a>

## 6. Shrink the failure

Try smaller worlds until none still fails. What is left is the bug and nothing else.

```javascript title="property.mjs"
// The shrinker: a smaller world that still breaks a property, until no
// smaller one does. Smaller is one answer fewer, or a yes turned into
// silence.
export async function shrink(compiled, answers) {
  let smallest = answers;
  for (let changed = true; changed; ) {
    changed = false;
    for (const candidate of smaller(smallest)) {
      if (broken(await run(compiled, candidate)).length) {
        smallest = candidate;
        changed = true;
        break;
      }
    }
  }
  return smallest;
}

function* smaller(answers) {
  for (let n = 0; n < answers.length; n++) yield answers.toSpliced(n, 1);
  for (let n = 0; n < answers.length; n++) if (answers[n]) yield answers.with(n, false);
}
```

[Shrink and trace](https://tinyactors.dev/property-testing/#shrink) · [live.mjs](https://tinyactors.dev/examples/property/live.mjs)

The smallest world is empty: the service never answers. The trace shows a fourth charge at 90 seconds.

<a id="ci"></a>

## 7. Run it in CI

The same module runs in Node.js and Bun. A failure names its seed.

```javascript title="main.mjs"
// The guide's runs, in Node.js. Run: node main.mjs
import { readFileSync } from 'node:fs';
import { broken, compile, run, search, shrink } from './property.mjs';

const chart = readFileSync(new URL('./payment.scxml', import.meta.url), 'utf8');
const show = (answers) => `[${answers.map((yes) => (yes ? 'answer' : 'silence')).join(', ')}]`;

const correct = compile(chart);
const found = await search(correct, 1000);
console.log(found ? `seed ${found.seed} breaks ${broken(found.run).join(', ')}` : '1000 worlds: every property held');

const buggy = compile(chart.replace('attempts &lt; 3', 'attempts &lt; 4')); // one retry too many
const failure = await search(buggy, 1000);
console.log(`seed ${failure.seed}: ${show(failure.run.answers)} breaks ${broken(failure.run).join(', ')}`);
const smallest = await shrink(buggy, failure.run.answers);
const replay = await run(buggy, smallest, { trace: true });
console.log(`shrunk to ${show(smallest)}: ${replay.charges.length} charges, ${replay.outcome}`);
console.log(`its trace: ${replay.spans.filter((span) => span.name.startsWith('scxml.macrostep')).map((span) => span.name.replace('scxml.macrostep ', '')).join(' → ')}`);
correct.close();
buggy.close();
```

```text title="output"
1000 worlds: every property held
seed 10: [silence, silence, silence, silence, silence, answer] breaks never more than three charges, gives up only after three charges
shrunk to []: 4 charges, failed
its trace: bootstrap → timeout → timeout → timeout → timeout
```

<a id="next"></a>

## Go further

There is no library to install. The world, the properties, the generator, the search and the shrinker are 76 lines of your own code.

- **Richer worlds**: Late, duplicate and reordered answers are more entries in the array.
- **More actors**: Generate the [team chat](https://tinyactors.dev/chat/index.md)'s inputs. Every online member sees every post.
- **Trace properties**: Spans are data. Assert on how a run got there, not only where it ended.

[Read the testing guide](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/docs/guide/testing.md) · [Build a team chat](https://tinyactors.dev/chat/index.md)
