Workers Test: Vitest Plugin, Integration Harness, and Breakpoint Debug
How to unit-test Workers in Vitest, run integration tests with createTestHarness, mock fetch, and debug locally with VS Code and DevTools.
This page summarizes Cloudflare Workers testing documentation. The platform splits work into fast unit tests inside the Workers runtime (Vitest plus @cloudflare/vitest-plugin) and integration tests against production-like builds from any Node.js runner (createTestHarness() in Wrangler). Local runs use Miniflare/workerd; that stack is useful for development but is not a hardened sandbox for untrusted code.
Workers test: Vitest unit tests vs createTestHarness() integration tests
Section titled “Workers test: Vitest unit tests vs createTestHarness() integration tests”Unit tests answer whether handlers, bindings, and runtime APIs behave correctly while you edit code. Integration tests answer whether built Workers, routes, and external mocks work together end to end.
| Goal | Tool | Runs in |
|---|---|---|
| Fast feedback on modules, bindings, Durable Objects | Workers Vitest integration (@cloudflare/vitest-plugin) |
workerd (same runtime as production Workers) |
| Production build, multi-Worker routes, Playwright, MSW in Node | createTestHarness() from Wrangler API |
Node test runner + local Worker server |
The Workers platform provides complementary tools for testing different parts of your application. For most projects, use the Workers Vitest integration for unit tests and the createTestHarness() API for integration tests.
— Cloudflare, Testing
For integration testing, Cloudflare now steers teams away from unstable_dev() and unstable_startWorker() toward createTestHarness(). Programmatic dev servers should use Vite’s createServer() with the Cloudflare Vite plugin, not the deprecated Wrangler dev APIs (Wrangler API, Migrate from unstable dev).
@cloudflare/vitest-plugin: how to set up Vitest for Workers
Section titled “@cloudflare/vitest-plugin: how to set up Vitest for Workers”The package formerly named @cloudflare/vitest-pool-workers is published as @cloudflare/vitest-plugin. The Vitest configuration API is unchanged; you update the dependency name, imports, and TypeScript types (changelog, Migrate to Vitest plugin).
Prerequisites (Write your first test):
compatibility_dateof2022-10-31or later- ES modules format Worker (not service worker format)
vitest@^4.1.0and@cloudflare/vitest-pluginas dev dependencies
Add the cloudflareTest() Vite plugin in vitest.config.ts and point at Wrangler config when you want production bindings mirrored in tests (Configuration):
import { cloudflareTest } from "@cloudflare/vitest-plugin";import { defineConfig } from "vitest/config";
export default defineConfig({ plugins: [ cloudflareTest({ wrangler: { configPath: "./wrangler.jsonc" }, }), ],});The plugin injects compatibility flags such as nodejs_compat during tests. Tests can pass while deploy would fail if you rely on Node globals without matching flags in wrangler.jsonc (Isolation and concurrency, Workers Best Practices).
Unit tests: call the handler with env and createExecutionContext()
Section titled “Unit tests: call the handler with env and createExecutionContext()”Import the Worker module and invoke worker.fetch(request, env, ctx) with helpers from cloudflare:test (Write your first test):
import { env } from "cloudflare:workers";import { createExecutionContext, waitOnExecutionContext } from "cloudflare:test";import worker from "../src";
const response = await worker.fetch(new Request("http://example.com/404"), env, createExecutionContext());await waitOnExecutionContext(ctx);Always await waitOnExecutionContext(ctx) before assertions when the handler uses ctx.waitUntil().
Integration-style Vitest tests: exports.default.fetch()
Section titled “Integration-style Vitest tests: exports.default.fetch()”exports from cloudflare:workers runs the main Worker in the same isolate as the test file, so global mocks affect it (Test APIs):
import { exports } from "cloudflare:workers";
const response = await exports.default.fetch("http://example.com/404");exports does not expose Assets; use the env.ASSETS binding or a harness-based integration test when you need asset behavior (Migrate from Vitest 3 to Vitest 4).
Storage isolation and concurrency in Vitest
Section titled “Storage isolation and concurrency in Vitest”Storage isolation is per test file. Test files run concurrently by default. To share storage across files (for example shared integration state), run Vitest with --max-workers=1 --no-isolate (Isolation and concurrency).
Cloudflare recommends awaiting every storage write, consuming full response bodies even when not asserted, and re-seeding data after reset() in harness tests where applicable (Known issues, Configure the test harness).
createTestHarness(): integration test harness lifecycle
Section titled “createTestHarness(): integration test harness lifecycle”createTestHarness() starts one or more Workers from Wrangler or Vite build output, wraps Miniflare, and exposes HTTP dispatch, scheduled events, logs, and binding introspection (Integration test harness, Get started).
Wrangler now provides createTestHarness(), an API for running integration tests against Workers built with Wrangler or the Cloudflare Vite plugin from any Node.js test runner.
— Cloudflare, Run integration tests against your Worker’s production build
Configure Workers, environments, and overrides
Section titled “Configure Workers, environments, and overrides”Point each harness entry at a Wrangler config; for Vite-built Workers, run vite build first (Configure the test harness). Optional per-Worker fields include env, vars, secrets, and bindingOverrides (Wrangler API).
If setup must run before config is known, call createTestHarness() without options, then server.update() before listen() (Configure the test harness).
Route dispatch and per-Worker handles
Section titled “Route dispatch and per-Worker handles”The first Worker in workers is primary. server.fetch() sends relative URLs to the primary Worker; absolute URLs match configured routes, otherwise fall back to primary (Interact with Workers). Use server.getWorker("name") to bypass routing and call fetch(), scheduled(), D1 migrations, Durable Object storage, or Workflow introspection (Wrangler API).
Typical lifecycle (Get started):
-
await server.listen()once per suite (beforeAll). -
await server.reset()after each test to recreate storage and restore initial options (afterEach). -
await server.close()when the suite ends (afterAll). -
On failure, call
server.debug()for runtime logs and a server timeline (Configure the test harness).
Mock outbound fetch() in Workers tests
Section titled “Mock outbound fetch() in Workers tests”Vitest unit tests: use @msw/cloudflare with setupNetwork(), enable in a Vitest setup file, and network.use() per test. The old fetchMock import from cloudflare:test was removed; use MSW or mock globalThis.fetch (Migrate from Vitest 3 to Vitest 4).
Integration harness: outbound Worker fetch() goes through Node’s globalThis.fetch, so MSW (setupServer from msw/node) or vi.spyOn(globalThis, "fetch") works (Integrations, Prepare test state). For binding-level fakes, use bindingOverrides to route a binding to a mock Worker in the same harness (Prepare test state).
Playwright can use a fixture that starts createTestHarness(), sets baseURL from listen(), and resets MSW plus harness state after each test (Integrations).
Durable Objects and cloudflare:test helpers
Section titled “Durable Objects and cloudflare:test helpers”Vitest runs Durable Object tests with real bindings via env and stubs (Testing Durable Objects):
runInDurableObject(stub, callback)— inspect instance and storage inside the object (Test APIs).runDurableObjectAlarm(stub)— run a scheduled alarm immediately.evictDurableObject(stub)/evictAllDurableObjects()— simulate eviction; durable storage survives, in-memory state resets (Test Durable Object eviction).listDurableObjectIds(namespace)— IDs visible only within the current test file’s isolation.
Access top-level exports in unit tests via createExecutionContext().exports or import { exports } from "cloudflare:workers" (Support for ctx.exports).
Breakpoint debug: wrangler dev, Vite, and Vitest --inspect
Section titled “Breakpoint debug: wrangler dev, Vite, and Vitest --inspect”Local Worker development (Wrangler or Vite)
Section titled “Local Worker development (Wrangler or Vite)”With Wrangler, breakpoint debugging works in DevTools and VS Code. The simplest path is a JavaScript Debug Terminal in VS Code, Cursor, or Windsurf: run wrangler dev or vite dev inside it and VS Code attaches automatically (Workers JavaScript debug terminals, Breakpoints).
Manual attach uses port 9229 and a .vscode/launch.json with "request": "attach" (Breakpoints).
With the Cloudflare Vite plugin, open the console Debug URL (for example http://localhost:5173/__debug) in Chrome for DevTools connected to local Workers (Vite plugin debugging, changelog). VS Code can attach via websocketAddress: "ws://localhost:9229/<NAME_OF_WORKER>" per Worker name in config (Vite plugin debugging).
Direct Miniflare debugging is an advanced path; most users should follow Workers Observability DevTools instead of Miniflare debugger attach alone.
Debug Vitest Worker tests
Section titled “Debug Vitest Worker tests”Run:
vitest --inspect --no-file-parallelismAttach to port 9229 (or --inspect=3456 / test.inspector.port in config). VS Code can use a compound launch config “Debug Workers tests” from Debugging Vitest integration (changelog).
Migration and deprecated APIs
Section titled “Migration and deprecated APIs”| From | To |
|---|---|
@cloudflare/vitest-pool-workers |
@cloudflare/vitest-plugin — run npx @cloudflare/codemods vitest:pool-workers-to-vitest-plugin (Migrate to Vitest plugin) |
unstable_dev() / unstable_startWorker() |
createTestHarness() for integration tests; Vitest plugin for in-runtime tests (Migrate from unstable dev) |
| Miniflare 2 Jest/Vitest environments | Vitest 4 + cloudflareTest(); Jest environment no longer provided (Migrate from Miniflare 2) |
import { env, SELF } from "cloudflare:test" |
import { env, exports } from "cloudflare:workers"; SELF.fetch → exports.default.fetch (Migrate from Vitest 3 to Vitest 4) |
Low-level control without Vitest or the harness remains possible via Miniflare writing tests; tests then run in Node while only the Worker runs in workerd.
Common mistakes
Section titled “Common mistakes”- Assuming green Vitest runs mean deploy-safe Node API usage without
nodejs_compatin Wrangler (Isolation and concurrency). - Using V8 native coverage; use Istanbul instead (Known issues).
- Expecting Vitest fake timers to expire KV/R2/cache simulators (Known issues).
- Starting/stopping
unstable_dev()per test instead of once per suite (Wrangler API). - Running untrusted Worker code locally without an appropriate VM/sandbox (Testing).
Further patterns live in Recipes and examples and Migration guides.
How to check this on your site
Section titled “How to check this on your site”- Install Vitest 4 and
@cloudflare/vitest-plugin, configurecloudflareTest()with yourwrangler.jsonc, and runnpx vitestper Write your first test. - Add a harness test:
createTestHarness({ workers: [{ configPath: "./wrangler.jsonc" }] }),listen/reset/close, and assert withserver.fetch()per Get started with the integration test harness. - If the Worker calls third-party HTTP APIs, enable MSW (
@msw/cloudflarefor Vitest ormsw/nodewith the harness) and fail on unhandled requests during a trial run (Mock outbound requests, Integrations). - Start
wrangler devorvite devin a JavaScript Debug Terminal (or open the Vite/__debugURL) and confirm breakpoints hit on a request (Breakpoints, DevTools). - You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about.