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()=>{const{ client }=awaitsetupTest(app);// Now you can interact with your actor through the clientconst myActor =await client.myActor.get();// Test your actor's functionalityawait myActor.someAction();// Make assertionsconst 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()=>{const{ client }=awaitsetupTest(app);const counter =await client.counter.get();// Initial stateexpect(await counter.getCount()).toBe(0);// Modify stateawait counter.increment();// Verify state was updatedexpect(await counter.getCount()).toBe(1);});
For actors that emit events, you can verify events are correctly triggered by subscribing to them:
import{ test, expect, vi }from"vitest";import{ setupTest }from"actor-core/test";import{ app }from"../src/index";test("actor should emit events",async()=>{const{ client }=awaitsetupTest(app);const chatRoom =await client.chatRoom.get();// Set up event handler with a mock functionconst mockHandler = vi.fn(); chatRoom.on("newMessage", mockHandler);// Trigger the eventawait chatRoom.sendMessage("testUser","Hello world");// Wait for the event to be emittedawait vi.waitFor(()=>{expect(mockHandler).toHaveBeenCalledWith("testUser","Hello world");});});
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()=>{// setupTest automatically configures vi.useFakeTimers()const{ client }=awaitsetupTest(app);const scheduler =await client.scheduler.get();// Set up a scheduled taskawait scheduler.scheduleTask("reminder",60000);// 1 minute in the future// Fast-forward time by 1 minuteawait vi.advanceTimersByTimeAsync(60000);// Verify the scheduled task executedexpect(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.