With the Workers Vitest plugin, how do you unit test a Worker's scheduled cleanup handler, including the work it hands to ctx.waitUntil()?
answer
- call the handler yourself
- a fake controller and a fake context
- createScheduledController() pins the time
- waitOnExecutionContext() before asserting
basics
~10 sImport the Worker module and call worker.scheduled(controller, env, ctx) yourself, with a controller from createScheduledController() and a ctx from createExecutionContext() in cloudflare:test; await waitOnExecutionContext(ctx) before asserting, so waitUntil work has settled.
solid answer
~40 sA Cron Trigger never fires inside a test, so the test plays the platform's part. `createScheduledController({ scheduledTime, cron })` from `cloudflare:test` builds the `ScheduledController` the handler receives; a fixed `scheduledTime` makes an "older than seven days" cutoff deterministic. `createExecutionContext()` builds the `ctx`. After `await worker.scheduled(controller, env, ctx)`, call `await waitOnExecutionContext(ctx)`: it waits for every promise passed to `ctx.waitUntil()` to settle, and it accepts only a context made by `createExecutionContext()`. Then assert on binding state through `env`, for example by counting the D1 rows left. Queue consumers follow the same pattern with `createMessageBatch()` and `getQueueResult()`, which also waits for `waitUntil` work and reports which messages were acknowledged or retried.
code
javascript · 40 linesimport { DurableObject } from "cloudflare:workers";
export class Counter extends DurableObject {
async increment() {
const count = ((await this.ctx.storage.get("count")) ?? 0) + 1;
await this.ctx.storage.put("count", count);
if ((await this.ctx.storage.getAlarm()) === null) {
await this.ctx.storage.setAlarm(Date.now() + 60 * 60 * 1000);
}
return count;
}
async read() {
return (await this.ctx.storage.get("count")) ?? 0;
}
async alarm() {
await this.ctx.storage.put("count", 0);
}
}
export default {
async fetch(request, env, ctx) {
const page = new URL(request.url).searchParams.get("page") ?? "home";
const counter = env.COUNTER.getByName(page);
if (request.method === "POST") {
const count = await counter.increment();
ctx.waitUntil(
env.DB.prepare("INSERT INTO visits (page, ts) VALUES (?, ?)").bind(page, Date.now()).run(),
);
return Response.json({ page, count });
}
return Response.json({ page, count: await counter.read() });
},
async scheduled(controller, env, ctx) {
const cutoff = controller.scheduledTime - 7 * 24 * 60 * 60 * 1000;
ctx.waitUntil(env.DB.prepare("DELETE FROM visits WHERE ts < ?").bind(cutoff).run());
},
};go deeper
Recall that the test calls worker.scheduled(controller, env, ctx) itself, building the controller and context with helpers from cloudflare:test.
Explain why awaiting the handler is not enough when it uses ctx.waitUntil(), what waitOnExecutionContext() waits for, and how a fixed scheduledTime makes date cutoffs testable.
Point out tests that pass only by timing because the local database answers fast, and push handler designs that read time from the controller and keep cron-specific branches testable.
Decide which background paths, scheduled and queue consumers alike, need handler-level tests in CI and which need a run against a deployed preview, given that the trigger wiring itself is never exercised here.
## Why the test calls the handler itself A Worker's `scheduled(controller, env, ctx)` handler normally runs when a **Cron Trigger** listed under `triggers.crons` in the Wrangler file fires. Nothing fires on a schedule inside a test run, so a unit test imports the Worker module and invokes the handler directly. The test supplies the three arguments the platform would supply: - **`controller`**: a `ScheduledController` carrying `scheduledTime` (milliseconds since the epoch) and `cron` (the cron string that fired). - **`env`**: the bindings, imported as `env` from `cloudflare:workers`, so the handler's D1, KV or Durable Object calls hit the plugin's local simulators. - **`ctx`**: an `ExecutionContext`, whose `waitUntil()` the handler may use to keep work running after it returns. ## The helpers in cloudflare:test | Helper | Builds or does | |---|---| | `createScheduledController(options?)` | A `ScheduledController`; `options.scheduledTime` takes a `Date` or a number and defaults to the current time, `options.cron` defaults to an empty string | | `createExecutionContext()` | A fresh `ExecutionContext` whose `waitUntil()` promises the test can await | | `waitOnExecutionContext(ctx)` | Waits until every promise passed to `ctx.waitUntil()` has settled; accepts only a context from `createExecutionContext()` | | `createMessageBatch(queueName, messages)` | A `MessageBatch` for a `queue()` handler | | `getQueueResult(batch, ctx)` | Waits for `waitUntil` work, then returns the batch's acknowledgement and retry state | ## Making time deterministic A cleanup job usually computes a cutoff from "now". If the handler reads `controller.scheduledTime` rather than `Date.now()`, the test controls "now" completely: 1. Pick a fixed instant, for example 03:00 UTC on a given day. 2. Seed rows on both sides of the cutoff, such as one 30 days old and one a minute old. 3. Build the controller with that instant as `scheduledTime` and the production cron string as `cron`. 4. Call the handler, wait on the context, and assert that only the old row is gone. A handler that branches on `controller.cron`, because one Worker serves several schedules, gets one test per cron string. Reading the clock through the controller is also a better production design: a late invocation keeps the time it was scheduled for. ## Why waitOnExecutionContext matters `ctx.waitUntil(promise)` lets a handler return while work continues. When the test awaits `worker.scheduled(...)`, it has waited for the handler's own promise only, not for the work passed to `waitUntil()`. An assertion made at that point races the delete it is checking. Locally the race can resolve in the test's favour, because the simulated database answers quickly, so the test passes by timing rather than by design and can fail later on a slower runner. Awaiting `waitOnExecutionContext(ctx)` removes the race, because the test now waits for exactly the work the handler scheduled, no more and no less. It accepts only a context from `createExecutionContext()`, so a hand-made object with a no-op `waitUntil` leaves that work running with nothing the test can await. ## The same pattern for queue consumers A `queue(batch, env, ctx)` handler is tested the same way. `createMessageBatch("cleanup-queue", messages)` builds the batch, where each message carries an `id`, a `timestamp`, an `attempts` count and a `body`. After calling the handler, `getQueueResult(batch, ctx)` returns: - `ackAll`: whether the handler acknowledged the whole batch. - `retryBatch`: whether the whole batch was retried, with any delay. - `explicitAcks`: the IDs passed to `message.ack()`. - `retryMessages`: the IDs passed to `message.retry()`, with any delay. ## What this test does not prove A handler-level test proves that, given a time and a cron string, the cleanup logic deletes the right rows. It deliberately leaves three things to other checks: - **The trigger wiring**: that `triggers.crons` in the Wrangler file contains the expression the handler expects, and that the deployed Worker has the trigger at all. - **The real schedule**: when the platform actually invokes the handler, and how late it can be. - **Production data volume**: a delete that is instant on ten seeded rows may need batching on a large table, which a unit test on a tiny fixture never shows. Keeping these out of the unit test is a feature: the test stays fast and deterministic, and each remaining risk has a named owner elsewhere, such as a configuration review or a run against a deployed preview. ## Mistakes to avoid - Asserting before `waitOnExecutionContext(ctx)` and trusting a pass that came from timing. - Reading `Date.now()` inside the handler, which forces the test to fake the clock. - Passing a plain object as `ctx`, which leaves `waitUntil()` work running with nothing to await it. - Testing the cron expression itself here: whether `0 3 * * *` fires at the intended hour is configuration, checked by reading the Wrangler file, not by this unit test.
- How would you test the Worker's queue() consumer the same way?Build a batch with `createMessageBatch("queue-name", messages)`, each message with `id`, `timestamp`, `attempts` and `body`, call `worker.queue(batch, env, ctx)` with a context from `createExecutionContext()`, then `await getQueueResult(batch, ctx)`. It waits for `waitUntil` work and returns `ackAll`, `retryBatch`, `explicitAcks` and `retryMessages`, so the test asserts which messages were acknowledged or retried.
- Why should the cleanup handler compute its cutoff from controller.scheduledTime instead of Date.now()?`controller.scheduledTime` is the instant the run was scheduled for, so a late invocation still cleans up relative to its slot, and a test sets it exactly with `createScheduledController({ scheduledTime })`. With `Date.now()`, the test would need to fake the clock, and production behaviour would drift with invocation delay.
- Awaiting worker.scheduled() already waits for everything passed to ctx.waitUntil().
- A plain object with an empty waitUntil method is as good a test ctx as createExecutionContext().
- A scheduled handler can only be tested by waiting for the real Cron Trigger.
- createScheduledController() always uses the current time, so cutoffs cannot be pinned.
- getQueueResult() returns before the handler's waitUntil promises settle.