콘텐츠로 이동
한국어

TestKit

이 콘텐츠는 아직 번역되지 않았습니다.

TestKit is a thin convenience wrapper around ActorSystem for tests. It gives you a ready-to-use system with sensible test defaults — quiet logger, easy probe creation, deterministic shutdown.

import { TestKit } from 'actor-ts/testkit';
const tk = TestKit.create('my-spec');
const probe = tk.createTestProbe();
const ref = tk.system.spawnAnonymous(() => new Worker(probe));
ref.tell({ kind: 'do' });
await probe.expectMessage('done');
await tk.shutdown();

Three things the kit does for you:

  • Builds the ActorSystem with a NoopLogger by default — no console spam during test runs.
  • Exposes createTestProbe() so you don’t have to thread the system into every probe constructor.
  • Owns shutdown() — call once at test end; safely tears down the system, scheduler, and dispatcher.
class TestKit {
static create(name?: string, options?: TestKitOptions): TestKit;
static withManualScheduler(name?, options?): { kit: TestKit; scheduler: ManualScheduler };
readonly system: ActorSystem;
createTestProbe(options?: TestProbeOptions): TestProbe;
within<T>(durationMs: number, callback: () => Promise<T>): Promise<T>;
shutdown(): Promise<void>;
}
interface TestKitOptions extends ActorSystemOptionsType {
quiet?: boolean; // default true — use NoopLogger
}

Builds a kit with a fresh system. The name is the system name — useful when running parallel test suites that mustn’t share state. Defaults to 'test-kit'.

const testKitOptions = TestKitOptions.create()
.withQuiet(false) // turn logging on
.withLogLevel(LogLevel.Debug)
.withConfig({ /* HOCON overrides */ });
const tk = TestKit.create('my-spec', testKitOptions);

With quiet: false you get console logs — useful when debugging a failing test. Otherwise, log calls are no-ops, which keeps your test output clean.

The kit is also the one place the message-boundary check is on by default: structured-clone = fail, so a message that would lose its prototype on a worker hop — a class instance where a plain object was meant — throws a MessageBoundaryError out of the tell that sends it. TestKitOptions.withMessageBoundary({ structuredClone: 'off' }) keeps a suite that sends class instances on purpose green.

const testProbeOptions = TestProbeOptions.create()
.withDefaultTimeoutMs(5_000) // default wait for expect/receive
.withName('order-probe');
const probe = tk.createTestProbe(testProbeOptions); // visible in logs
ref.tell({ kind: 'do', replyTo: probe });
await probe.expectMessage({ kind: 'done' });

Returns a TestProbe scoped to this kit’s system. See TestProbe for the full expectations API.

await tk.within(1_000, async () => {
ref.tell({ kind: 'do' });
await probe.expectMessage('done');
});

Run callback and assert it completed in under durationMs. Throws if it took longer. Useful for “this should be fast” SLAs inside tests, without depending on the test runner’s per-test timeout.

Note: this is a soft deadline — callback still runs to completion even if it overshoots. It just throws after the fact.

afterEach(async () => {
await tk.shutdown();
});

Terminates the underlying system. Always call this in a fixture teardown — without it, the test process leaks a live system that keeps the event loop alive. Some test runners (Bun, Vitest) detect this and fail the suite; others hang.

const { kit, scheduler } = TestKit.withManualScheduler('my-spec');
const ref = kit.system.spawnAnonymous(() => new Heartbeat(probe));
ref.tell({ kind: 'start' });
scheduler.advance(5_000); // jump 5 virtual seconds
await probe.expectMessage('tick');

Returns both the kit and its ManualScheduler so the test can advance virtual time. See ManualScheduler for the full virtual-clock semantics.

import { describe, it, beforeEach, afterEach } from 'bun:test';
describe('Counter', () => {
let tk: TestKit;
let probe: TestProbe;
beforeEach(() => {
tk = TestKit.create();
probe = tk.createTestProbe();
});
afterEach(async () => {
await tk.shutdown();
});
it('increments', async () => {
const ref = tk.system.spawnAnonymous(Counter);
ref.tell({ kind: 'increment' });
ref.tell({ kind: 'get', replyTo: probe as ActorRef<number> });
await probe.expectMessage(1);
});
});

A fresh kit per test — no state leakage between tests, slightly slower than sharing one kit but worth it for isolation.

describe('PureBehaviorTests', () => {
let tk: TestKit;
beforeAll(() => { tk = TestKit.create(); });
afterAll(async () => { await tk.shutdown(); });
// each `it` uses tk.createTestProbe() for its own probe, but the
// underlying ActorSystem is shared.
});

Faster than per-test setup; only safe when tests don’t mutate shared actors.

The TestKit API reference covers the full surface.

Every deadline in the testkit — TestProbe’s 3 s default, MultiNodeSpec’s 10 s awaitTimeoutMs, ParallelMultiNodeSpec’s 30 s and its handshake and control RPC, and every awaitCondition budget — goes through one multiplier. Set it for a whole run:

Terminal window
ACTOR_TS_TEST_TIME_FACTOR=3 bun test tests/multi-node/

The default is 1, so the feature is inert until somebody asks for it. A malformed value throws rather than falling back to 1: the variable is set by someone who wants slower deadlines, and ignoring their typo would hand them the failure they were trying to fix. Every message the factor lengthened names it:

awaitCondition: the cluster converged did not become true within 6000ms
(ACTOR_TS_TEST_TIME_FACTOR=3, so this budget is 3x the declared one)

Use virtual time instead, wherever it applies

Section titled “Use virtual time instead, wherever it applies”

This is not a substitute for ManualScheduler. Where a test can advance a clock it should: virtual time removes the race rather than widening it, and a deadline that cannot be reached beats one that is merely generous. The factor is for what is left over — convergence waits, probe timeouts, barrier waits — where a real cluster really does take real time.

These are failure budgets, not expected durations. Nothing is asserted on them; they exist to turn a hang into a message. That is what makes them safe to scale, and it is the same reason the opposite rule holds for an elapsed-time assertion: a test that asserts something took less than N ms is asserting the machine’s speed, and no factor makes that correct.

The per-test cap does not scale, and the guard says so

Section titled “The per-test cap does not scale, and the guard says so”

Bun’s per-test timeout is not something the factor can reach: it is either the 5 000 ms default or a literal third argument to test(). A factor that quietly tripled a 4 000 ms budget under an untouched 5 000 ms cap would recreate exactly the failure AwaitConditionBudgets exists to prevent — the runner’s timeout wins the race, and the budget’s message, the one naming what was awaited, is never printed.

So the guard scales with the factor. Run it at a raised one and it reports every test whose budget can no longer report, rather than certifying them. A test that should keep working at a raised factor declares its cap through scaledMs, which the guard recognises:

test('the cluster converges', async () => {
await spec.awaitMembers('a', 3);
}, scaledMs(30_000)); // rises with the factor, like the budgets inside it

Which means a raised factor is a per-suite tool, not a global switch: at factor 3 over the whole tree the guard reports about 1 200 tests whose literal caps no longer contain their budgets, and it is right to. The three suites that nightly-flakes.yml runs at factor 3 declare scaledMs caps for that reason.