With the Workers Vitest plugin, how do you test a Durable Object counter's stored state and its alarm without waiting for real time?
answer
- call the stub as production does
- runInDurableObject(stub, callback)
- the instance and its state
- runDurableObjectAlarm() fires it now
- only classes in the main Worker
basics
~10 sCall the Durable Object through a stub as production code does, then use runInDurableObject(stub, (instance, state) => ...) to read state.storage directly, and runDurableObjectAlarm(stub) to run a scheduled alarm immediately.
solid answer
~40 sGet a stub from the namespace binding, for example `env.COUNTER.getByName("home")`, and call its RPC methods; that tests the public contract. To check what was persisted, `runInDurableObject(stub, async (instance, state) => ...)` from `cloudflare:test` runs the callback inside that object with the live class instance and its `DurableObjectState`, so `state.storage.get("count")` and `state.storage.getAlarm()` can be asserted. `runDurableObjectAlarm(stub)` runs and removes a scheduled alarm at once and returns `true`, or `false` when none was set, so an hour-long reset is tested in milliseconds. `evictDurableObject(stub)` tears down the instance but keeps its storage, which proves state is reloaded from storage rather than memory. These helpers work only for classes defined in the main Worker.
code
javascript · 23 linesimport { env } from "cloudflare:workers";
import { evictDurableObject, runDurableObjectAlarm, runInDurableObject } from "cloudflare:test";
import { expect, it } from "vitest";
import { Counter } from "../src/index.js";
it("stores the count, schedules a reset alarm and survives eviction", async () => {
const stub = env.COUNTER.getByName("home");
expect(await stub.increment()).toBe(1);
const alarm = await runInDurableObject(stub, async (instance, state) => {
expect(instance).toBeInstanceOf(Counter);
expect(await state.storage.get("count")).toBe(1);
return state.storage.getAlarm();
});
expect(alarm).not.toBeNull();
await evictDurableObject(stub);
expect(await stub.read()).toBe(1);
expect(await runDurableObjectAlarm(stub)).toBe(true);
expect(await stub.read()).toBe(0);
expect(await runDurableObjectAlarm(stub)).toBe(false);
});go deeper
Recall that tests call the object through a stub from the binding, and that runInDurableObject() and runDurableObjectAlarm() come from cloudflare:test.
Explain what the runInDurableObject() callback receives, how runDurableObjectAlarm() fires and removes an alarm with a true or false result, and why these work only for main-Worker classes.
Use eviction to prove state comes back from storage rather than memory, and recognise per-file isolation, disposal with using and unawaited writes as the usual causes of flaky Durable Object tests.
Set the balance between contract tests through stubs and internal-state tests, so refactors of a class's storage layout do not break dozens of tests that only needed the public behaviour.
## Two layers to test A **Durable Object** is a class whose instances each have a unique ID, single-threaded execution and their own persistent storage. Testing one well means checking two layers: - **The contract**: what callers get back from the object's RPC methods or `fetch()`. - **The internals**: what the object persisted, which alarm it scheduled, and whether it recovers after its in-memory instance is gone. The Workers Vitest plugin runs the class inside `workerd` with real Durable Object semantics and local storage, and `cloudflare:test` adds helpers that reach into an instance without changing production code. ## Calling through the stub `env.COUNTER.getByName("home")` returns a stub for the object named "home"; `idFromName()` followed by `get()`, or `newUniqueId()`, work as they do in production. Awaiting `stub.increment()` calls the RPC method exactly as a Worker would. This layer catches serialisation surprises and contract regressions, and it should carry most assertions, because it is what callers depend on. Choose object names with the storage model in mind. Because storage is shared by every test in a file, a name such as "home" reused across tests carries counts from one test into the next. Deriving the name from the test, or generating one with `crypto.randomUUID()`, gives every test its own object and keeps the assertions independent without any reset step. ## Looking inside with runInDurableObject `runInDurableObject(stub, callback)` temporarily replaces the object's `fetch()` handler with the callback, sends it a request, and returns the callback's result. The callback receives: 1. `instance`: the live instance of the class, so a test can call internal methods, spy on them or inspect fields. 2. `state`: the object's `DurableObjectState`, so `state.storage.get()`, `state.storage.put()` or `state.storage.getAlarm()` read or seed persisted data. A common use is seeding storage before calling a method, for example putting a count of 99 to test a rollover rule. ## Alarms without waiting An object schedules work with `ctx.storage.setAlarm(time)`, and the runtime calls its `alarm()` handler at that time. A test should not sleep for an hour. `runDurableObjectAlarm(stub)` runs the scheduled alarm **immediately** and removes it, returning `true` if an alarm ran and `false` if none was scheduled. Calling it twice therefore proves the handler did not reschedule itself, and asserting `false` on a fresh object proves no alarm was set by accident. ## A worked sequence for the counter For a counter whose `increment()` stores a count and schedules a one-hour reset alarm, one test can walk the whole life cycle: 1. Call `stub.increment()` and expect `1`, which checks the contract. 2. Inside `runInDurableObject()`, assert that `state.storage.get("count")` is `1` and that `state.storage.getAlarm()` is not `null`, which checks persistence and scheduling. 3. Call `evictDurableObject(stub)`, then `stub.read()`, and expect `1` again, which proves the count came from storage after the instance was torn down. 4. Call `runDurableObjectAlarm(stub)` and expect `true`, then `stub.read()` and expect `0`, which proves the alarm handler reset the count. 5. Call `runDurableObjectAlarm(stub)` once more and expect `false`, which proves the handler did not schedule another alarm. Each step fails for a different reason, so a red test points straight at the broken layer. ## Eviction and resets | Helper | Effect | Stored data | |---|---|---| | `evictDurableObject(stub)` | Gracefully tears down one running instance; by default hibernatable WebSockets are hibernated, and in-flight requests get up to 30 seconds to drain | Kept | | `evictAllDurableObjects()` | The same for every running object in evictable namespaces | Kept | | `abortAllDurableObjects()` | Forcibly tears down all instances without waiting for in-flight requests | Kept | | `reset()` | Deletes all data from all bound storage | Deleted | | `listDurableObjectIds(namespace)` | Lists IDs created in this test file's storage | Unchanged | `evictDurableObject()` is the honest test for a class that caches state in fields: after eviction, the next call constructs a new instance, and only what was written to storage survives. It rejects if the object is not currently running. ## Limits to know - `runInDurableObject()`, `runDurableObjectAlarm()` and `evictDurableObject()` work only with stubs pointing at classes defined in the **main** Worker, the one named by `main` or the Wrangler file, not in an auxiliary Worker. - Storage is isolated **per test file**, so an object named "home" in one test still holds that test's count in the next test of the same file. - WebSockets on Durable Objects are not supported with per-file storage isolation; such tests run with shared storage through Vitest's `--max-workers=1 --no-isolate` flags. - RPC methods that return non-primitive values, such as an `RpcTarget`, should be received with `using` so stubs are disposed and the file's storage can be cleaned up. - Every storage call in a test should be awaited; a dangling write can break the per-file cleanup.
- If the stub already returns the count, why use runInDurableObject() at all?Assertions through the stub test the contract and should carry most of the suite. `runInDurableObject()` adds what the contract hides: the alarm time an object scheduled, keys it persisted but never returns, seeding storage into an edge state before a call, or spying on an internal method. Use it for those, not to replace contract tests.
- What does evictDurableObject() prove that runInDurableObject() cannot?That the object survives losing its in-memory instance. Eviction tears down the instance but keeps storage, so the next call builds a fresh instance; if a value lived only in a field, the test sees it vanish. By default it hibernates hibernatable WebSockets and waits up to 30 seconds for in-flight requests, and it rejects when the object is not running.
- Why might listDurableObjectIds() return fewer IDs than the whole suite created?It respects per-file storage isolation: it lists only the objects created in the current test file's storage. Objects created by other test files live in their own isolated storage and are invisible here, which is the intended behaviour, not a lost write.
- runInDurableObject() works for a class defined in any auxiliary Worker.
- runDurableObjectAlarm() waits until the alarm's scheduled time arrives.
- evictDurableObject() deletes the Durable Object's stored data along with the instance.
- Contract tests through the stub are redundant once you can inspect the instance directly.
- A field set on the instance survives evictDurableObject() because the object keeps its ID.