skip to content

With Cloudflare's Workers Vitest plugin, how do you make tests run inside workerd with your Wrangler bindings, and how does a test call the Worker?

level: juniorimportance: should knowfreq 35%

answer

  1. a Vite plugin in the Vitest config
  2. cloudflareTest() reads the Wrangler file
  3. a miniflare block for test-only bindings
  4. env and exports from cloudflare:workers
  5. exports.default.fetch() for integration

basics

~10 s

Add cloudflareTest() from @cloudflare/vitest-plugin to the Vitest config's plugins with wrangler.configPath set, so test files run in workerd with the Worker's bindings. Tests import env and exports from cloudflare:workers and call exports.default.fetch().

solid answer

~40 s

Install `vitest` (4.1 or later) and `@cloudflare/vitest-plugin` as dev dependencies, then add `cloudflareTest({ wrangler: { configPath: "./wrangler.jsonc" } })` to the `plugins` array of a `defineConfig()` Vitest config. The plugin reads `main`, the compatibility settings and the bindings from that file and runs each test file inside `workerd` through Miniflare, fully locally. A `miniflare` block adds test-only bindings or overrides, and its values win over the Wrangler file. In a test, `import { env, exports } from "cloudflare:workers"`: `env` holds the bindings, and `exports.default.fetch(url)` sends a request through the main Worker's default export in the same isolate as the test. For a unit test, import the Worker module and call `worker.fetch(request, env, ctx)` with a context from `createExecutionContext()` in `cloudflare:test`.

code

javascript · 11 lines
javascript
import { cloudflareTest } from "@cloudflare/vitest-plugin";
import { defineConfig } from "vitest/config";

export default defineConfig({
  plugins: [
    cloudflareTest({
      wrangler: { configPath: "./wrangler.jsonc" },
      miniflare: { kvNamespaces: ["TEST_FIXTURES"] },
    }),
  ],
});

go deeper

for a junior

Recall the three moving parts: cloudflareTest() in the Vitest config, the Wrangler file it reads, and env plus exports imported from cloudflare:workers. Be ready to write one exports.default.fetch() assertion.

for a middle

Explain the difference between calling worker.fetch() with createExecutionContext() and calling exports.default.fetch(), and how the miniflare block merges over the Wrangler file with miniflare winning.

for a senior

Show where this setup diverges from a deployed Worker: Vite module resolution in the shared isolate, global mocks reaching the Worker, no static assets through exports, and when an auxiliary Worker is worth its limits.

for a principal

Treat the plugin as the team's fast, credential-free inner loop, and be explicit about which checks it cannot replace and who keeps the test config in step with the Wrangler file.

## What the plugin does The **Workers Vitest integration** is the npm package `@cloudflare/vitest-plugin`. It makes Vitest, the test runner, execute test files inside **`workerd`**, the open-source runtime behind Cloudflare Workers, instead of inside Node.js. Miniflare starts `workerd` on the developer's machine or the CI runner and simulates the bindings, so a test talks to a local KV namespace, R2 bucket, D1 database or Durable Object through the same binding methods the Worker uses in production. Nothing reaches Cloudflare's network unless a binding is explicitly configured as remote. What that buys a team: - **The Worker's own runtime**: web-standard APIs, the `cloudflare:` modules and binding methods behave as `workerd` implements them, not as a Node.js mock imagines them. - **Storage isolated per test file**: writes made in one test file are not visible to another. - **No account needed**: no login, no API token and no deploy, which suits CI. - **Fast reruns**: watch mode reuses the Workers and their module caches between runs where it can. ## Configuring it 1. Install `vitest` 4.1 or later and `@cloudflare/vitest-plugin` as dev dependencies. 2. In `vitest.config`, export `defineConfig()` from `vitest/config` and put `cloudflareTest()` in its `plugins` array. 3. Point `wrangler.configPath` at the Wrangler file; `.jsonc`, `.json` and `.toml` all work. 4. Add a `miniflare` block only for what tests need beyond production, such as a fixture KV namespace. | `cloudflareTest()` option | What it controls | |---|---| | `wrangler.configPath` | Loads `main`, the compatibility date and flags, and the bindings | | `wrangler.environment` | Picks one Wrangler environment's bindings and vars | | `miniflare` | Miniflare worker options merged over the file; on overlap these win | | `main` | The entry point loaded in the same isolate as the tests; read from the Wrangler file when omitted | `cloudflareTest()` also accepts an optionally async function that returns the options. That is how a value computed in Node.js while the config loads, such as migrations read from disk, reaches the tests. ## Two ways to call the Worker | Style | Call | Good for | |---|---|---| | Unit | `import worker from "../src/index.js"`, then `worker.fetch(request, env, ctx)` with `createExecutionContext()` and `waitOnExecutionContext()` from `cloudflare:test` | One handler with full control over `env` and `ctx` | | Integration | `exports.default.fetch("https://example.com/path")` with `exports` from `cloudflare:workers` | The request path through the default export, as a client would hit it | Both styles run the Worker in the **same isolate as the test**. A global mock set in the test, for example a spy on `globalThis.fetch`, therefore reaches the Worker too, and the Worker's imports go through Vite's module resolution, which differs subtly from a deployed bundle. When that matters, an **auxiliary Worker** listed in `miniflare.workers` runs in a fresh environment with ordinary Workers module resolution, at the cost of needing compiled JavaScript and losing access to `cloudflare:test`. `exports` reaches only the Worker's handlers, not its static assets. ## Types for TypeScript projects - Run `wrangler types` to generate the `Env` interface and the runtime types. - Add `@cloudflare/vitest-plugin/types` to the `types` array of the test `tsconfig.json`, so `cloudflare:test` and `cloudflare:workers` type-check. - Declare `interface ProvidedEnv extends Env {}` inside a `declare module "cloudflare:workers"` block to type `env` in tests. ## Mistakes that cost a debugging session - **Duplicating bindings by hand** in the `miniflare` block instead of reading the Wrangler file, so tests and production drift apart the first time someone adds a binding to only one of them. - **Expecting a dev server**: `exports.default.fetch()` dispatches straight to the Worker's handler, so there is no dev-server URL for a test to call. - **Forgetting the explicit wait**: in a unit test, asserting `ctx.waitUntil()` side effects before `await waitOnExecutionContext(ctx)` makes the result depend on timing. - **Treating local as remote**: the bindings are local simulators, so a test proves the Worker's logic against the binding API, not the global behaviour of the real service. - **Pre-building a mocked `Response`**: a stub for `globalThis.fetch` should create its `Response` inside the mock implementation, because an I/O object made in the test's context cannot be read from the Worker's request context. ## What changed recently - The package was renamed from `@cloudflare/vitest-pool-workers` to `@cloudflare/vitest-plugin` at 1.0.0 with the API unchanged; a codemod, `vitest:pool-workers-to-vitest-plugin`, rewrites dependencies, imports and the test `tsconfig.json`. - In the Vitest 4 rework before that, `defineWorkersConfig()`, `defineWorkersProject()` and the `test.poolOptions.workers` block were removed; their options now go straight into `cloudflareTest()`. - `env` and `SELF` exported from `cloudflare:test` are deprecated in favour of `env` and `exports` from `cloudflare:workers`, and `fetchMock` was removed. Older tutorials that start from any of these describe a configuration the current plugin does not accept or no longer recommends.

  • How do you stub an outbound fetch() the Worker makes during an exports.default.fetch() test?
    The main Worker shares the test's isolate, so a global mock reaches it: spy on `globalThis.fetch` and build the `Response` inside the mock implementation. A `Response` created in the test's context and returned pre-built fails with "Cannot perform I/O on behalf of a different request". The old `fetchMock` helper from `cloudflare:test` was removed; a request-mocking library is the documented alternative. Auxiliary Workers ignore global mocks.
  • When is an auxiliary Worker worth its limits?
    When the Worker under test must run in a fresh environment with ordinary Workers module resolution rather than Vite's, closer to a deployed bundle. Auxiliary Workers are listed in `miniflare.workers` and bound to from tests, but they need JavaScript entry points (compile first, for example with `wrangler deploy --dry-run --outdir dist`), cannot import `cloudflare:test`, and are not affected by global mocks set in tests.

  • Configure it with defineWorkersConfig() and a test.poolOptions.workers block.
  • The plugin runs tests in Node.js with the bindings replaced by hand-written mocks.
  • exports.default.fetch() sends a real HTTP request to a running wrangler dev server.
  • The miniflare block is ignored once wrangler.configPath is set.
  • New integration tests should import env and SELF from cloudflare:test.

Assumes @cloudflare/vitest-plugin 1.4.0 (renamed from @cloudflare/vitest-pool-workers at 1.0.0) with Vitest 4.1 or later; cloudflareTest() replaced defineWorkersConfig() in the Vitest 4 rework.