Tests Answer Different Questions at Each Layer
A green unit test can still deploy a broken Worker. Imagine a small webhook relay. It receives a payload, checks an HMAC signature against a secret, writes the event to KV, and returns 202. A developer writes a unit test that passes a hand-built environment object containing a fake binding, calls the handler, and asserts the fake recorded the write. The test is green. The code is then uploaded to a branch preview, where every request returns 500. The preview's configuration never declared the binding, so the real one is missing and the runtime throws before the handler writes anything. The unit test was not wrong about the logic. It was answering a different question.
That gap is the article's subject. A unit test exercises your code with dependencies replaced or simplified. A runtime integration test runs the whole Worker module inside the Workers runtime, with bindings backed by a local emulator such as Miniflare. A hosted smoke test sends a request to a deployed copy and checks the response, headers, and side effects that only exist on Cloudflare. None replaces the others, because each sits behind a different boundary.
Three terms matter before configuration. A version is an immutable snapshot of your Worker's bundled code, static assets, bindings, and compatibility settings. A deployment decides which version or versions receive traffic. A Preview is a branch-scoped hosted copy of the Worker with its own URL and, for some resources, its own storage. Keeping them distinct makes a safe release possible.
The useful analogy is flight testing: a simulator is cheap and repeatable, a taxi test proves the systems work together on the ground, and a supervised test flight proves the aircraft under real conditions. You would not board passengers after only the simulator, and you would not skip the simulator because you have a test flight. Figure 1 shows the same progression for a Worker, including the failure each layer is designed to catch.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["Unit test
handler + fake env"] --> B{"Logic correct?"}
B -->|"yes"| C["Runtime integration
workerd + local bindings"]
B -->|"no"| X["Fix code"]
C --> D{"Bindings resolve
in local config?"}
D -->|"no"| Y["Fail fast:
missing binding"]
D -->|"yes"| E["Preview
branch-isolated resources"]
E --> F{"Hosted route, secret,
and binding agree?"}
F -->|"no"| Z["Block promotion:
1101 or auth drift"]
F -->|"yes"| G["Hosted smoke
0% version or canary"]
G --> H{"Production path
within budget?"}
H -->|"no"| R["Roll back or hold"]
H -->|"yes"| I["Promote to 100%"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class A,B,C,X,D,E,F,H,R,I secondary;
class Y,Z danger;
class G warn;
The trust boundary is the important part, not the number of tests. Everything left of the preview runs on hardware you control, so you can inspect it, reset it, and run it offline. Everything right of it runs on Cloudflare, where routes, secrets, service bindings, and resource identities come from account state rather than from your laptop. Figure 2 draws that boundary explicitly: the runtime can be identical on both sides while the configuration and data are not.
Runtime Tests and Real Service Bindings
Let the runtime execute the module. Cloudflare's current Vitest integration is a dedicated plugin package that replaced the older pool package in 2026. It runs Vitest inside the Workers runtime using Miniflare, gives tests access to the runtime modules, and isolates storage per test file. Setup is a plugin call pointed at your Wrangler configuration.
Current testing package
The supported integration is @cloudflare/vitest-plugin, which replaced @cloudflare/vitest-pool-workers in 2026 and requires Vitest 4.1 or later.
Tests can import from cloudflare:workers and cloudflare:test.
Two integration styles plus one escape hatch.
| Style | What executes | Use it when |
|---|---|---|
| Handler import | Your Worker module and worker.fetch() with a context from createExecutionContext() | You want the handler in the test runner's module graph |
| Default export | exports.default.fetch() as an entrypoint | You want a real request shape but can still share Vite resolution |
| Auxiliary Worker | A separate Worker entrypoint in the test harness | Module-level state matters |
The same webhook route can be checked at five levels, each with a different blind spot.
| Mechanism | What executes | Isolation boundary | Evidence it gives you |
|---|---|---|---|
| Unit test importing the handler | Your function with a hand-built env and stubbed dependencies | Local process, no network | Response shape, branching, and business logic |
Vitest runtime test via exports.default.fetch() | The Worker entrypoint in workerd with Miniflare-backed bindings | Local per-test-file storage | Routing, middleware, and binding calls through the runtime |
wrangler dev --remote | The Worker in a Cloudflare preview environment with remote bindings | Only the resources you configure | Behavior against real services while you debug |
wrangler preview | A branch copy under the same Worker with previews settings | Per-Preview Durable Objects and containers; KV, D1, and R2 only if separate IDs | Hosted routing, secrets, and bindings on a branch URL |
Version URL after wrangler versions upload | One uploaded version | Production resources for that version | The exact artifact you may later deploy |
| Gradual deployment at 0–10% | Production deployment with two versions | Real production data and traffic | Production behavior before full promotion |
The table also exposes a product boundary. Previews are the recommended branch workflow, but they are not a clone of production. A Preview gets its own Durable Object namespace and container instances automatically. KV, D1, R2, Queues, Vectorize, Hyperdrive, and Workflows are isolated only when bound to separate resources. Service bindings from a Preview call the bound Worker's production deployment. Queue consumers and Cron Triggers do not target a Preview. Version URLs run one uploaded version with production resources, so they inspect an artifact rather than test a branch.
Figure 3 traces a runtime test and a hosted check through a binding, including the two failure branches that matter most: a missing local binding and a drifted previews block.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
sequenceDiagram
autonumber
participant CI as CI job
participant W as Worker in workerd
participant B as Binding (KV, D1, R2)
CI->>W: exports.default.fetch("/webhook")
W->>B: env.HOOKS.put(key, body)
alt binding exists
B-->>W: success
W-->>CI: 202 Accepted
else binding missing or misnamed
B-->>W: runtime error 1101
W-->>CI: 500
end
CI->>W: GET preview URL /health
alt previews block matches top level
W-->>CI: 200 {"ok":true}
else previews block drifted
W-->>CI: 500 or stale response
end
A test becomes evidence when the shell around it can fail. The widget below pairs a minimal release-gate test with the shell steps that turn it into a gate. The test panel assumes the plugin is registered in the Vitest config and that the Worker exposes a webhook route and a health route; the shell panel runs type generation, tests, uploads, a Preview deployment, a hosted smoke request, and promotion.
Secrets follow their own lifecycle. A Preview is created with a copy of the base secret values, not a live link to production.
Secrets are copied at creation
Shared Preview secrets are set once in the Previews base configuration and copied into each new Preview at creation. Changing the base later affects only new Previews; an existing Preview keeps the old value until you update it. Previews do not inherit production secrets, and secrets.required is validated during a version upload or deploy, so a missing required secret can fail before traffic moves.
Previews Are Not the Same as Production
A green Preview is not a production proof. The most expensive misconception in this area is that a Preview passing its checks proves the production configuration is valid. It does not. A Preview is a separate environment with its own settings, and the things it cannot exercise are exactly the things that tend to break at 2 a.m.: Cron Triggers, Queue consumers, production routes, and cross-Worker service bindings.
Describe what a Preview does prove. A Preview is excellent evidence that the branch builds, that the route responds, that a secret is present, and that a binding points at something. It is weak evidence about production data shape, scheduled execution, and downstream Workers, because those live outside the Preview's boundary.
A green Preview proves Preview configuration only
A Preview that returns 200 proves the branch works with the Preview's configuration, not with production's. If the previews block drifts from the top-level block, or the Worker depends on Cron Triggers, Queue consumers, or service bindings, a healthy Preview can coexist with a broken production deploy.
Drift arrives through ordinary settings. Four differences explain most false greens.
| Setting | Preview behavior | Failure it creates |
|---|---|---|
| Top-level vars | Not inherited; the previews block must repeat them | The environment variable is undefined on the branch |
| D1 binding | Isolated only when the previews block names a separate database | The branch passes against stale staging rows |
| Preview URL | Public by default; workers.dev sends X-Robots-Tag: noindex | Noindex is not access control; add Cloudflare Access for custom-domain hostnames with sensitive content |
| Base secrets | Copied at Preview creation, not synchronized later | A rotation silently leaves old credentials in place |
Make configuration observable. Return the environment name and the version ID from a health route, then compare the Preview response, the Version URL response, and the production response. A mismatch in APP_ENV is a configuration defect, not a routing mystery. The version metadata binding and structured logs support the same comparison without exposing internals.
Rollbacks Need Code and Data Compatibility
A rollback moves traffic, not data.
A rollback is not a time machine
wrangler rollback creates a new deployment that routes 100% of traffic to a previously published version. It does not restore deleted KV namespaces, undo a D1 migration, recreate an R2 bucket, or reverse a Durable Object class lifecycle change. It is refused if a bound resource was deleted or if a Durable Object lifecycle change occurred between the target and active versions, and it can target only the 100 most recently published versions.
The rule: the previous version must remain compatible with the data written by the version you are rolling back from. Schema changes need an expand-and-contract sequence. Add the new column or table, deploy code that can read both shapes, backfill, switch reads, and only then remove the old field in a later release. If the release drops a column that the previous version still selects, rollback either fails at the platform boundary or succeeds into a 500 loop.
A composite incident shows the shape. A team ships version 42 with a D1 migration that renames email to email_normalized and updates the query. Version 41 is still the rollback target. The migration runs before promotion, the rename drops the old column, and version 41's query for the old column fails. The deployment can move but the data cannot. The outage lasts until they add the old column back and backfill it.
The safe release is shown in the top half of Figure 4: the migration adds a column, both versions can read the old one, and rollback is boring. The bottom half shows the destructive version, where the rollback target no longer matches the schema.
Canaries reduce rollback pressure, not compatibility work.
Version skew needs a data plan
Gradual deployments route a percentage of requests to a new version, and version overrides send a specific request to a version even when it is at 0%. That lets you smoke-test production code before exposing it to real traffic. The tradeoff is version skew: consecutive requests from one user can hit different versions unless you set the Cloudflare-Workers-Version-Key header for affinity. Any state that spans requests, including carts, sessions, and Durable Objects, needs a compatibility plan for the skew window.
Build a Small Worker Release Gate
A design-only lab: prove the gate fails before it passes. It has not been executed for this article, and no timing, error rate, or cost result is claimed. Run it against a controlled Worker and a dedicated preview namespace.
Build a Small Worker Release Gate
Status: design-only, not executed. No Wrangler command, Preview deployment, or hosted request was run for this article.
Prerequisites. Node.js 20 or later, Wrangler 4.135.0 or later (required for Previews), Vitest 4.1 or later, the Vitest plugin, and a Cloudflare account with a workers.dev subdomain. Previews work on Free and Paid plans; documented limits are 100 Previews per Worker on Free, 500 on Paid, and 100 deployments per Preview. Use a dedicated KV namespace, never a production namespace.
Setup. Create a Worker named gate-demo with a current compatibility date, a required webhook secret, and a previews block that binds HOOKS to the dedicated namespace. The health route returns ok plus the environment name; the webhook route returns 401 unless an x-signature header is present. Keep the test-only secret in a local dev-vars file.
- Install the pinned toolchain from the widget.
- Run the suite. Expect two passing tests: the unsigned webhook returns 401, and the health route returns 200 with JSON.
- Create the Preview. Expect a Preview URL and a separate deployment URL.
- Request both routes on the Preview URL. Expect health 200 with the preview environment, and the unsigned webhook 401.
- Remove HOOKS from the previews block only, leaving the top-level binding intact, redeploy, and request both routes again.
- Restore the binding and promote only after the hosted check passes. For the full gate, upload a tag, create a 0% deployment, smoke it with the version-overrides header, then move traffic in steps.
| Observation | Local suite | Hosted Preview |
|---|---|---|
| Before the defect | Two passing tests | Health 200, unsigned webhook 401 |
| After removing the Preview binding | Still passing | Binding error such as 1101 |
Expected observation. The defect is invisible locally and visible to the hosted check, so the gate stops before promotion.
Failure checks. If the local test fails after removing HOOKS, you edited the top-level block. If the hosted request still returns 200, confirm you are hitting the new deployment URL rather than an older Preview URL.
Cost. The exercise consumes Preview deployments, Worker requests, KV operations, and version storage. No paid add-ons are required, but repeated runs count against the limits above; check current pricing before running at scale.
Cleanup. Delete the Preview, delete the dedicated namespace, and remove the local secret file. Tagged versions age out of the 100-version retention window.
Demonstrate a Failing Check Blocks a Bad Release
Four independent signals, one gate. Each fails for a different reason, and any non-zero step stops the pipeline before deployment.
| Signal | Command | Fails when |
|---|---|---|
| Logic | npx vitest run | A handler assertion breaks |
| Types | npx wrangler types --check | The generated Env type no longer matches the configuration |
| Build and validation | npx wrangler versions upload --dry-run | Bundling or configuration validation fails |
| Hosted response | curl --fail on the Preview | The route returns non-2xx |
The failing-check trace is deliberately simple. The unsigned webhook test expects 401. A regression changes the handler to return 200 for every request. Vitest reports one failed assertion and exits 1; the workflow never uploads a version. If the regression lives only in the hosted configuration, the local suite passes, the Preview smoke request returns 500 or a binding error, and the smoke check exits non-zero. Neither result was measured for this article.
Why can a green unit test still ship a 1101? The unit test supplied the binding object itself. 1101 means the Worker referenced a binding the runtime did not provide, a configuration fact the unit test never checked. The runtime test and Preview close that gap.
Does wrangler rollback undo a D1 migration? No. It creates a new deployment pointing at an older version; the schema and rows are unchanged. That is why the previous version must stay compatible with the new schema.
When should you use a Version URL instead of a Preview? Use a Version URL to inspect one exact uploaded artifact before deploying it, knowing it uses production resources. Use a Preview for an isolated branch environment.
Previews have hard edges
Previews cannot consume Queues, do not run Cron Triggers, and cannot bind to another Worker's matching Preview through a service binding. D1 isolation needs a separate database per branch; sharing one staging database is a common source of drift. Preview base secrets are copied at creation, not continuously synchronized.
The tooling moves quickly. The Vitest package was renamed in 2026, Version URLs were previously called preview URLs, and Previews require a recent Wrangler. Verify current commands and limits before copying any of this into a pipeline.
Verification and versions. Documentation was checked on 2026-11-05 against the pages listed below. Previews require Wrangler 4.135.0 or later. The Vitest integration is @cloudflare/vitest-plugin and requires Vitest 4.1 or later. Gradual deployments require Wrangler 3.40.0 or later, with older versions needing the --x-versions flag. Rollbacks cover the 100 most recently published versions. No command in this article was executed, and no pricing, latency, or error-rate measurement is claimed.
Authoritative references. Workers testing: https://developers.cloudflare.com/workers/testing/ · Vitest integration: https://developers.cloudflare.com/workers/testing/vitest-integration/ · Write your first test: https://developers.cloudflare.com/workers/testing/vitest-integration/write-your-first-test/ · Previews: https://developers.cloudflare.com/workers/previews/ · Preview configuration: https://developers.cloudflare.com/workers/previews/configuration/ · Preview resources and isolation: https://developers.cloudflare.com/workers/previews/resources/ · Versions and deployments: https://developers.cloudflare.com/workers/versions-and-deployments/ · Gradual deployments: https://developers.cloudflare.com/workers/versions-and-deployments/gradual-deployments/ · Rollbacks: https://developers.cloudflare.com/workers/versions-and-deployments/rollbacks/ · Version overrides: https://developers.cloudflare.com/workers/versions-and-deployments/version-overrides/ · Wrangler environments: https://developers.cloudflare.com/workers/wrangler/environments/ · Wrangler Workers commands: https://developers.cloudflare.com/workers/wrangler/commands/workers/ · CI/CD: https://developers.cloudflare.com/workers/ci-cd/ · Observability: https://developers.cloudflare.com/workers/observability/
Next in the Series
In Coordinate State With Durable Objects, we'll explore Model object identity, transactions, and realtime sessions.