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
ActorSystemwith aNoopLoggerby 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.
The API
Section titled “The API”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}TestKit.create(name?, options?)
Section titled “TestKit.create(name?, options?)”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.
tk.createTestProbe(options?)
Section titled “tk.createTestProbe(options?)”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.
tk.within(durationMs, callback)
Section titled “tk.within(durationMs, callback)”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.
tk.shutdown()
Section titled “tk.shutdown()”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.
TestKit.withManualScheduler()
Section titled “TestKit.withManualScheduler()”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 secondsawait 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.
Fixture patterns
Section titled “Fixture patterns”Per-test fixture (Bun, Vitest, Jest)
Section titled “Per-test fixture (Bun, Vitest, Jest)”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.
Shared fixture for read-only tests
Section titled “Shared fixture for read-only tests”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.
What TestKit doesn’t do
Section titled “What TestKit doesn’t do”Where to next
Section titled “Where to next”- Testing overview — the big picture: unit, time-deterministic, multi-node.
- TestProbe — the fake-actor expectations API.
- ManualScheduler — virtual time.
- MultiNodeSpec — for cluster scenarios.
The TestKit API reference
covers the full surface.
Scaling every deadline at once
Section titled “Scaling every deadline at once”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:
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 itWhich 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.
