Skip to content

Vitest integration

For most users, Cloudflare recommends using the Workers Vitest integration for unit testing Workers and Pages Functions projects. Vitest ↗︎ is a popular JavaScript testing framework featuring a fast watch mode, Jest compatibility, and default TypeScript support. Cloudflare provides the @cloudflare/vitest-plugin Vite plugin, which runs your Vitest tests inside the Workers runtime.

The Workers Vitest integration:

  • Supports both unit tests and integration tests.
  • Provides direct access to Workers runtime APIs and bindings.
  • Implements isolated per-test-file storage.
  • Runs tests in a local Workers runtime using Miniflare.
  • Leverages Vitest's hot-module reloading for near instant reruns.
  • Supports projects with multiple Workers.

Write your first test

If you use @cloudflare/vitest-pool-workers, refer to Migrate to Vitest plugin.

Offline and local binding support

@cloudflare/vitest-plugin runs tests inside a local workerd runtime. Miniflare simulates many storage and compute bindings without a network connection. Other bindings have limited local support or need a remote connection unless you mock them.

Binding Offline support in Vitest Notes and testing strategy
KV, D1, R2, Durable Objects, Queues, Workflows Simulated locally Use cloudflare:test helpers to apply D1 migrations, run Durable Object alarms, or inspect Workflows.
Service Bindings, Rate Limiting Simulated locally For service bindings, configure auxiliary Workers under miniflare.workers or override handlers with miniflare.serviceBindings.
Email (send_email) Simulated locally, no delivery Miniflare logs outgoing emails and saves message content and attachments to local files. Spy on send() to check payloads or mock errors.
Static Assets (ASSETS) Direct binding calls Call env.ASSETS.fetch() to serve configured local files. exports.default.fetch() calls the Worker handler directly and skips asset routing. Use createTestHarness() to test asset-first routing.
Images Limited local simulation The local simulator supports .info() and a subset of transformations, such as resizing and rotation. Use remote: true for the full Images API.
Browser Run Local Chrome or mock Local Chrome has limited feature support. For offline CI, cache Chrome before disconnecting and use local test pages, or mock the binding.
Hyperdrive Direct connection to a local database Use localConnectionString to connect directly to a database that can run offline, or mock your database client. A remote binding uses your deployed Hyperdrive configuration.
Workers AI, Media Transformations Remote only (mock offline) These bindings connect remotely by default. Set remote: true to suppress the configuration warning. Remote calls can incur usage charges.
Vectorize, mTLS Remote only (mock offline) Set remote: true to connect. Omitting remote warns and leaves the binding unavailable.

For the full per-binding breakdown across wrangler dev, the Cloudflare Vite plugin, and wrangler dev --remote, refer to Supported bindings per development mode.

Run tests offline in CI

To run binding tests in CI without Cloudflare credentials or remote usage charges, disable the remote binding proxy and mock calls to remote-only bindings. For a fully offline run, also mock outbound fetch() requests or use local resources. Disabling the proxy does not block network access.

  1. Set remoteBindings: false in cloudflareTest() to stop Vitest from starting a remote proxy session. Do not set remote: false on Workers AI, Media Transformations, Vectorize, or mTLS bindings. Wrangler rejects that setting because those bindings have no local implementation.

    vitest.config.tsts
    import { cloudflareTest } from "@cloudflare/vitest-plugin";
    import { defineConfig } from "vitest/config";
    
    export default defineConfig({
    	plugins: [
    		cloudflareTest({
    			remoteBindings: false,
    			wrangler: { configPath: "./wrangler.jsonc" },
    		}),
    	],
    });
  2. Stub the remote-only bindings with vi.spyOn() on env, or inject test doubles with withEnv() from cloudflare:workers. This example uses the /ai and /vectorize routes from the AI and Vectorize Vitest recipe ↗︎. It checks that each route calls its mock and returns the mocked result.

    test/offline.spec.jsjs
    import { env, exports } from "cloudflare:workers";
    import { afterEach, expect, it, vi } from "vitest";
    
    afterEach(() => {
    	vi.restoreAllMocks();
    });
    
    it("returns embeddings from the Workers AI mock", async () => {
    	const embeddings = {
    		shape: [2, 2],
    		data: [
    			[0.1, 0.2],
    			[0.3, 0.4],
    		],
    	};
    	const run = vi.spyOn(env.AI, "run").mockResolvedValue(embeddings);
    
    	const response = await exports.default.fetch("https://example.com/ai");
    
    	expect(run).toHaveBeenCalledExactlyOnceWith("@cf/baai/bge-base-en-v1.5", {
    		text: [
    			"This is a story about an orange cloud",
    			"This is a story about a llama",
    		],
    	});
    	expect(await response.json()).toEqual(embeddings);
    });
    
    it("returns a mutation ID from the Vectorize mock", async () => {
    	const result = { mutationId: "test-mutation" };
    	const upsert = vi.spyOn(env.VECTORIZE, "upsert").mockResolvedValue(result);
    
    	const response = await exports.default.fetch("https://example.com/vectorize");
    
    	expect(upsert).toHaveBeenCalledExactlyOnceWith([
    		expect.objectContaining({ id: "123" }),
    		expect.objectContaining({ id: "456" }),
    	]);
    	expect(await response.json()).toEqual(result);
    });
    test/offline.spec.tsts
    import { env, exports } from "cloudflare:workers";
    import { afterEach, expect, it, vi } from "vitest";
    
    afterEach(() => {
    	vi.restoreAllMocks();
    });
    
    it("returns embeddings from the Workers AI mock", async () => {
      const embeddings = {
        shape: [2, 2],
        data: [
          [0.1, 0.2],
          [0.3, 0.4],
        ],
      };
      const run = vi.spyOn(env.AI, "run").mockResolvedValue(embeddings);
    
      const response = await exports.default.fetch("https://example.com/ai");
    
      expect(run).toHaveBeenCalledExactlyOnceWith("@cf/baai/bge-base-en-v1.5", {
        text: [
          "This is a story about an orange cloud",
          "This is a story about a llama",
        ],
      });
      expect(await response.json()).toEqual(embeddings);
    });
    
    it("returns a mutation ID from the Vectorize mock", async () => {
      const result = { mutationId: "test-mutation" };
      const upsert = vi.spyOn(env.VECTORIZE, "upsert").mockResolvedValue(result);
    
      const response = await exports.default.fetch("https://example.com/vectorize");
    
      expect(upsert).toHaveBeenCalledExactlyOnceWith([
        expect.objectContaining({ id: "123" }),
        expect.objectContaining({ id: "456" }),
      ]);
      expect(await response.json()).toEqual(result);
    });

Was this helpful?