# Write Tests for a Cloudflare Worker With Durable Objects

Yes. An agent adds Vitest tests that run inside workerd for your Worker's routes, WebSocket sessions and Durable Objects, in a pull request with the test output.

[Run this on Rush](https://cloud.getrush.ai/run/write-unit-tests/cloudflare-workers/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the Worker and its configuration before writing a test, because Durable Objects decide how the tests must run. In a Worker laid out like cloudflare/workers-chat-demo, `wrangler.toml` names the script `edge-chat-demo` with `main = "src/chat.mjs"`, a `compatibility_date` of 2024-01-01, two Durable Object bindings, `rooms` for `ChatRoom` and `limiters` for `RateLimiter`, a `[[rules]]` entry that imports `*.html` as `Data`, and a `v1` migration with `new_sqlite_classes`. `package.json` has no dependencies and no scripts, and the only workflow is Semgrep. `src/chat.mjs` is the whole server: the default `fetch` serves `chat.html` at `/`, routes `/api/...` to `handleApiRequest`, and answers 404 otherwise; `POST /api/room` returns `env.rooms.newUniqueId()` and any other method is 405; `/api/room/<name>/...` resolves a 64-hex name with `idFromString`, a name up to 32 characters with `idFromName` and answers 404 for longer, then forwards the rest of the path to the room's `fetch`, which only accepts `/websocket` with an `Upgrade` header.

The room logic is the part worth testing. `ChatRoom` uses the WebSocket Hibernation API: `handleSession` calls `state.acceptWebSocket`, stores the rate limiter id in the socket's attachment, and queues a `joined` message for each named session plus the last 100 messages from `storage.list({reverse: true, limit: 100})`; `webSocketMessage` treats the first frame as the join, rejects a name over 32 characters with close code 1009, answers `{ready: true}`, then enforces a 256-character message limit, a monotonic `timestamp`, broadcasts to every session and writes the message under its ISO timestamp key. `RateLimiter` keeps `nextAllowedTime` in memory only, adds 5 seconds per `POST` and returns a cooldown once more than 20 seconds are queued, and `RateLimiterClient` in the room blocks a session that is over it with an error frame instead of a broadcast.

It adds `vitest` and `@cloudflare/vitest-pool-workers`, plus `wrangler` as a dev dependency, and a `vitest.config.mjs` that uses `defineWorkersConfig` with `wrangler: { configPath: "./wrangler.toml" }`, so the tests run inside workerd with the real bindings, the Data rule for the HTML import and isolated Durable Object storage per test. `test/worker.test.mjs` uses `SELF.fetch` for the HTTP paths: `/` answers HTML, `POST /api/room` answers 64 hex characters, `GET /api/room` is 405, a 33-character name is 404, and `/api/room/lobby/websocket` without an `Upgrade` header is 400. `test/chat-room.test.mjs` opens two sockets to the same room through `SELF.fetch` with `Upgrade: websocket`, accepts `response.webSocket`, sends `{name}` on each and asserts the first sees `{joined}` for the second, that a 257-character message gets `{error}` and no broadcast, that a second room has an empty backlog, and, by reconnecting, that the backlog carries the earlier message in order. `test/rate-limiter.test.mjs` uses `runInDurableObject` on a `limiters` stub to `POST` five times and read a cooldown above zero.

Each test sends `CF-Connecting-IP` explicitly, because `handleSession` keys the limiter on that header and a missing one would share a limiter across every test. The agent adds `"test": "vitest run"` to `package.json`, runs `npm install` and `npm test` in its sandbox, and puts the summary in the pull request. It changes `src/chat.mjs` only if a test is impossible without it, and says so; the one candidate it names is the error frame that returns `err.stack`, which a test can only match loosely.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Write tests for this Cloudflare Worker. Read wrangler.toml, package.json, README.md and all of src/chat.mjs first; there are no tests today. Add vitest, @cloudflare/vitest-pool-workers and wrangler as dev dependencies, a vitest.config.mjs using defineWorkersConfig with the wrangler.toml path so the tests run inside workerd with the rooms and limiters Durable Object bindings and the HTML Data rule, and a test script. Write test/worker.test.mjs for the HTTP routes through SELF.fetch (HTML at /, a 64-hex id from POST /api/room, 405 on GET, 404 on a 33-character name, 400 on /websocket without Upgrade), test/chat-room.test.mjs that opens two WebSockets to one room with a CF-Connecting-IP header, joins each with a name and asserts the joined broadcast, the ready frame, the 256-character message limit and the backlog a reconnecting socket receives in order, and test/rate-limiter.test.mjs that uses runInDurableObject to POST five times and read a positive cooldown. Do not change src/chat.mjs unless a test cannot be written otherwise, and say so. Run npm install and npm test in your sandbox and open a pull request with the output.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

The pull request adds `vitest.config.mjs`, three files under `test/`, and the dev dependencies and `test` script in `package.json` with a `package-lock.json`. Its description quotes the Vitest summary with each test name, the pool's note about which `compatibility_date` and bindings it loaded from `wrangler.toml`, and the versions it pinned, so a reviewer can see the tests ran in workerd and not in Node.

`src/chat.mjs` and `wrangler.toml` are unchanged. Where a behaviour was awkward to assert, such as the `err.stack` error frame or the exact cooldown number, the test asserts the shape and the description says why the number is not pinned.

Before merging, a reviewer decides whether to run `npm test` in a workflow beside the existing Semgrep one, and whether the rate limiter's in-memory counter, which the tests show resets with the object, is the behaviour they want in production.

## Run it on every night

An automation with a `schedule` trigger, `cron` `0 2 * * *` and your `timezone`, runs this prompt in the Project's repository each night. On a Worker that already has the pool configured, the agent reads the existing `test/` files and writes tests for the paths they miss, so the second night adds cases rather than a second config; a night with nothing left to cover ends with a note and no pull request.

Each run opens one pull request on its own branch with the test output in its description. `max_runs_per_hour` on the automation keeps a mis-set schedule from starting more than one.

## Why run it on Rush?

Durable Objects cannot be tested by importing the module into Node: `state.acceptWebSocket`, `serializeAttachment`, `storage.list` and `idFromName` only exist inside the Workers runtime. The agent sets up the Workers Vitest pool, which runs the tests in workerd with the bindings from `wrangler.toml`, and proves the setup in its own sandbox before the pull request, so the tests exercise the same hibernation API and storage the deployed Worker uses.

Every command and its output is kept on the run, including the pool's startup lines and each test's result, so the reviewer sees the suite run without installing Wrangler. Several Workers can get their first tests at once, each in its own sandbox, and nothing merges until a person reads them.

## Frequently asked questions

### Why the Workers Vitest pool and not plain Vitest with mocks?

The chat room is written against the WebSocket Hibernation API and Durable Object storage, which have no Node equivalent to mock faithfully. `@cloudflare/vitest-pool-workers` runs each test file inside workerd with the bindings, migrations and module rules from `wrangler.toml`, so `env.rooms.idFromName` and `state.getWebSockets` are the real ones. Storage is isolated per test, which is also why the backlog test can rely on a fresh room.

### How can a test open a WebSocket to a Durable Object?

Through `SELF.fetch` with an `Upgrade: websocket` header: the response's `webSocket` property is the client end, and the test calls `accept()` on it, sends JSON frames and collects `message` events. The room sees it exactly as it sees a browser, including the `CF-Connecting-IP` header the test sets so each test gets its own rate limiter.

### Does it need a Cloudflare account or wrangler login?

No. The pool uses Wrangler only to read `wrangler.toml` and start a local workerd; nothing is deployed and no token is used. `npm test` runs offline in the sandbox and in CI the same way.

### What about the HTML import in chat.mjs?

`import HTML from "./chat.html"` depends on the `[[rules]]` entry in `wrangler.toml` that marks `*.html` as `Data`. The pool applies the same rules, so the import resolves in tests and the `/` route test can assert the page's content type and a known string from `chat.html`.

### Will it change the Worker to make it testable?

The prompt forbids it unless a test cannot be written otherwise, and the pull request lists any such case. In this Worker the routes and the room are reachable through `SELF.fetch` and `runInDurableObject` as written, so the expected diff is tests, config and `package.json` only.

## More Cloudflare Workers jobs

- [Write Vitest Tests for a Cloudflare Worker](https://getrush.ai/run/write-workers-vitest-tests/cloudflare-workers/)
- [Add API Key Authentication to a Cloudflare Worker API](https://getrush.ai/run/add-api-key-auth/cloudflare-workers/)
- [Add CORS to a Cloudflare Worker API](https://getrush.ai/run/add-cors/cloudflare-workers/)

## The same job on other stacks

- [Write Unit Tests for a Cobra CLI](https://getrush.ai/run/write-unit-tests/cobra/)
- [Write Unit Tests for a Deno App](https://getrush.ai/run/write-unit-tests/deno/)
- [Write Unit Tests for a .NET App](https://getrush.ai/run/write-unit-tests/dotnet/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
