ActorCore provides a straightforward testing framework to build reliable and maintainable applications. This guide covers how to write effective tests for your actor-based services.
ActorCore includes a test helper called setupTest that configures a test environment with in-memory drivers for your actors. This allows for fast, isolated tests without external dependencies.
import { test, expect } from "vitest";import { setupTest } from "actor-core/test";import { app } from "../src/index";test("my actor test", async (test) => { const { client } = await setupTest(test, app); // Now you can interact with your actor through the client const myActor = await client.myActor.get(); // Test your actor's functionality await myActor.someAction(); // Make assertions const result = await myActor.getState(); expect(result).toEqual("updated");});
The test framework uses in-memory drivers that persist state within each test, allowing you to verify that your actor correctly maintains state between operations.
import { test, expect } from "vitest";import { setupTest } from "actor-core/test";import { app } from "../src/index";test("actor should persist state", async (test) => { const { client } = await setupTest(test, app); const counter = await client.counter.get(); // Initial state expect(await counter.getCount()).toBe(0); // Modify state await counter.increment(); // Verify state was updated expect(await counter.getCount()).toBe(1);});
ActorCore’s schedule functionality can be tested using Vitest’s time manipulation utilities:
import { test, expect, vi } from "vitest";import { setupTest } from "actor-core/test";import { app } from "../src/index";test("scheduled tasks should execute", async (test) => { // setupTest automatically configures vi.useFakeTimers() const { client } = await setupTest(test, app); const scheduler = await client.scheduler.get(); // Set up a scheduled task await scheduler.scheduleTask("reminder", 60000); // 1 minute in the future // Fast-forward time by 1 minute await vi.advanceTimersByTimeAsync(60000); // Verify the scheduled task executed expect(await scheduler.getCompletedTasks()).toContain("reminder");});
The setupTest function automatically calls vi.useFakeTimers(), allowing you to control time in your tests with functions like vi.advanceTimersByTimeAsync(). This makes it possible to test scheduled operations without waiting for real time to pass.