shiichan

Now you can trigger Durable Object eviction on demand in your tests!

Hey there, it's me, Shiichan! Today I found a little update that makes testing Durable Objects a bit nicer, so let me share it with you.

Cloudflare Changelog developers.cloudflare.com

What was announced?

On the Cloudflare Changelog, two new test helpers, evictDurableObject and evictAllDurableObjects, were added to @cloudflare/vitest-pool-workers. Both are imported from cloudflare:test and used inside your Vitest tests.

The story so far

A Durable Object can be evicted from memory when it stays idle for a while. That's a normal part of the production Durable Object lifecycle. But when you wanted to test whether your state gets restored correctly after an eviction, there was no way to reproduce that eviction on your own schedule.

What changes

With the new helpers, you can now trigger eviction at any point inside a test. That lets you actually check whether state is re-read from storage, and how your WebSocket behavior holds up.

Dive Deep

Here is how you use them.

import { evictDurableObject, evictAllDurableObjects } from "cloudflare:test";
import { env } from "cloudflare:workers";

const id = env.COUNTER.idFromName("my-counter");
const stub = env.COUNTER.get(id);

// Evict the Durable Object instance pointed to by a specific stub
await evictDurableObject(stub);

// Close WebSockets instead of hibernating them
await evictDurableObject(stub, { webSockets: "close" });

// Evict all currently-running Durable Objects in evictable namespaces
await evictAllDurableObjects();

Pass a single stub to evictDurableObject and it evicts just that instance. Add { webSockets: "close" } to test the behavior where WebSockets are closed instead of hibernated. evictAllDurableObjects clears out every running instance in evictable namespaces at once. These are available in @cloudflare/vitest-pool-workers@0.16.20 and later. For more, check the Test APIs reference and the Testing Durable Objects guide.

Wrap-up

  • evictDurableObject and evictAllDurableObjects were added to cloudflare:test
  • You can reproduce eviction in a test and verify state restoration and WebSocket behavior afterward
  • Add { webSockets: "close" } to test closing WebSockets instead of hibernating
  • Available in @cloudflare/vitest-pool-workers@0.16.20 and later

This one is perfect for anyone building stateful apps with Durable Objects who also wants to lock down their tests!