Review how the Workers Vitest integration runs tests and imports modules. By default, it isolates local storage per test file, not per individual test.
When you run your tests with the Workers Vitest integration, Vitest will:
- Read and evaluate your configuration file using Node.js.
- Run any
globalSetup↗︎ files using Node.js. - Collect and sequence test files.
- For each Vitest project, depending on its configured isolation and concurrency, start one or more
workerd↗︎ processes, each running one or more Workers. - Run
setupFiles↗︎ and test files inworkerdusing the appropriate Workers. - Watch for changes and re-run test files using the same Workers if the configuration has not changed.
By default, the Workers Vitest integration isolates local storage per test file, not per individual test. Writes to local KV, R2, D1, Durable Objects, or the Cache API from one test file (*.test.ts or *.spec.ts) are not visible to other test files.
The Workers Vitest integration reuses Workers and their module caches between test runs where possible. A copy of all auxiliary workers exists in each workerd process.
By default, test files run concurrently. To make test files share the same local storage (for example, for integration tests that depend on shared state), use the Vitest flags --max-workers=1 --no-isolate.
Tests in the same file share local storage. Choose a cleanup strategy based on what your tests need to preserve:
- Delete only data created by the test: Remove test-created D1 rows, KV keys, or R2 objects in
afterEach(). This preserves schemas and shared fixtures. - Use unique IDs or key prefixes per test: Generate an ID with
crypto.randomUUID()for Durable Object names (idFromName()), KV keys, or R2 object keys. Scope queries and listings to the test's own data, since unfiltered operations still see shared state. - Reset local storage between sequential tests: Call
reset()fromcloudflare:testwith@cloudflare/vitest-pool-workersv0.15.0 or later, or with@cloudflare/vitest-plugin. This clears stored data, including D1 tables and migration history. It does not restore seeded data or clear remote bindings. - Split tests into separate files: With default isolation on, move tests that require independent storage into separate
*.test.tsfiles. This is useful for testing initial migrations or listing every key in a namespace.
Do not use reset() or whole-table deletes between concurrent tests in the same file. Cleanup can remove data another test is still using.
Use local bindings in both examples. Set remoteBindings: false in cloudflareTest() if your Worker configuration uses remote bindings. With a remote D1 binding, SQL writes and deletes affect the remote database.
This example uses local DB, KV, and BUCKET bindings, and a COUNTER Durable Object that returns its count from /increment. It assumes an items table with id and name text columns. It deletes only the test row and uses unique IDs for keyed storage operations.
import { env } from "cloudflare:workers";
import { afterEach, describe, expect, it } from "vitest";
describe("D1 row cleanup", { concurrent: false }, () => {
const itemId = crypto.randomUUID();
afterEach(async () => {
await env.DB.prepare("DELETE FROM items WHERE id = ?").bind(itemId).run();
});
it("writes a test row", async () => {
await env.DB.prepare("INSERT INTO items (id, name) VALUES (?, ?)")
.bind(itemId, "first")
.run();
const item = await env.DB.prepare("SELECT name FROM items WHERE id = ?")
.bind(itemId)
.first();
expect(item).toEqual({ name: "first" });
});
it("does not see the previous test's row", async () => {
const item = await env.DB.prepare("SELECT name FROM items WHERE id = ?")
.bind(itemId)
.first();
expect(item).toBeNull();
});
});
it("uses a unique ID for Durable Objects, KV keys, and R2 objects", async () => {
const testId = crypto.randomUUID();
const stub = env.COUNTER.get(env.COUNTER.idFromName(testId));
const response = await stub.fetch("https://example.com/increment");
expect(await response.text()).toBe("1");
const kvKey = `${testId}:status`;
await env.KV.put(kvKey, "ready");
expect(await env.KV.get(kvKey)).toBe("ready");
const r2Key = `${testId}/report.txt`;
await env.BUCKET.put(r2Key, "ok");
const object = await env.BUCKET.get(r2Key);
expect(await object?.text()).toBe("ok");
});import { env } from "cloudflare:workers";
import { afterEach, describe, expect, it } from "vitest";
describe("D1 row cleanup", { concurrent: false }, () => {
const itemId = crypto.randomUUID();
afterEach(async () => {
await env.DB.prepare("DELETE FROM items WHERE id = ?").bind(itemId).run();
});
it("writes a test row", async () => {
await env.DB.prepare("INSERT INTO items (id, name) VALUES (?, ?)")
.bind(itemId, "first")
.run();
const item = await env.DB.prepare("SELECT name FROM items WHERE id = ?")
.bind(itemId)
.first();
expect(item).toEqual({ name: "first" });
});
it("does not see the previous test's row", async () => {
const item = await env.DB.prepare("SELECT name FROM items WHERE id = ?")
.bind(itemId)
.first();
expect(item).toBeNull();
});
});
it("uses a unique ID for Durable Objects, KV keys, and R2 objects", async () => {
const testId = crypto.randomUUID();
const stub = env.COUNTER.get(env.COUNTER.idFromName(testId));
const response = await stub.fetch("https://example.com/increment");
expect(await response.text()).toBe("1");
const kvKey = `${testId}:status`;
await env.KV.put(kvKey, "ready");
expect(await env.KV.get(kvKey)).toBe("ready");
const r2Key = `${testId}/report.txt`;
await env.BUCKET.put(r2Key, "ok");
const object = await env.BUCKET.get(r2Key);
expect(await object?.text()).toBe("ok");
});To clear local storage between tests, await reset() in afterEach(). Because reset() drops D1 tables and migration history, reapply migrations in beforeEach(), not just once in beforeAll() or a setup file.
This example uses local DB and KV bindings, plus a TEST_MIGRATIONS binding populated with readD1Migrations(). The migrations create an empty items table with id and name columns.
import { applyD1Migrations, reset } from "cloudflare:test";
import { env } from "cloudflare:workers";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
describe("local storage reset", { concurrent: false }, () => {
beforeEach(async () => {
await applyD1Migrations(env.DB, env.TEST_MIGRATIONS);
});
afterEach(async () => {
await reset();
});
it("writes to KV and D1", async () => {
await env.KV.put("status", "ready");
await env.DB.prepare("INSERT INTO items (id, name) VALUES (?, ?)")
.bind("1", "first")
.run();
expect(await env.KV.get("status")).toBe("ready");
expect(await env.DB.prepare("SELECT name FROM items").first()).toEqual({
name: "first",
});
});
it("starts with empty KV and a fresh D1 table", async () => {
expect(await env.KV.get("status")).toBeNull();
const { results } = await env.DB.prepare("SELECT * FROM items").all();
expect(results).toHaveLength(0);
});
});import { applyD1Migrations, reset } from "cloudflare:test";
import { env } from "cloudflare:workers";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
describe("local storage reset", { concurrent: false }, () => {
beforeEach(async () => {
await applyD1Migrations(env.DB, env.TEST_MIGRATIONS);
});
afterEach(async () => {
await reset();
});
it("writes to KV and D1", async () => {
await env.KV.put("status", "ready");
await env.DB.prepare("INSERT INTO items (id, name) VALUES (?, ?)")
.bind("1", "first")
.run();
expect(await env.KV.get("status")).toBe("ready");
expect(await env.DB.prepare("SELECT name FROM items").first()).toEqual({
name: "first",
});
});
it("starts with empty KV and a fresh D1 table", async () => {
expect(await env.KV.get("status")).toBeNull();
const { results } = await env.DB.prepare("SELECT * FROM items").all();
expect(results).toHaveLength(0);
});
});Each Worker has its own module cache. As Workers are reused between test runs, their module caches are also reused. Vitest invalidates parts of the module cache at the start of each test run based on changed files.
The Workers Vitest plugin runs code inside a Cloudflare Worker that Vitest would usually run inside a Node.js Worker thread ↗︎. To make this possible, the plugin automatically injects the nodejs_compat, [no_nodejs_compat_v2] and export_commonjs_default compatibility flags. This is the minimal compatibility setup that still allows Vitest to run correctly, but without pulling in polyfills and globals that are not required. If you already have a Node.js compatibility flag defined in your configuration, the Vitest plugin does not add those flags.