Cloudflare Docs
Workers
Edit this page on GitHub
Set theme to dark (⇧+D)

Get started


For most users, Cloudflare recommends using the Workers Vitest integration for testing Workers and Pages Functions projects. Vitest is a popular JavaScript testing framework featuring a very fast watch mode, Jest compatibility, and out-of-the-box support for TypeScript. In this integration, Cloudflare provides a custom pool that allows your Vitest tests to run inside the Workers runtime.

Get started with the Vitest integration Get started guide, and refer to Recipes for testing different types of Workers.

The Workers Vitest integration…

  • Supports both unit tests and integration tests.
  • Provides direct access to Workers runtime APIs and bindings.
  • Implements isolated per-test storage.
  • Runs tests fully-locally using Miniflare.
  • Leverages Vitest’s hot-module reloading for near instant reruns.
  • Provides a declarative interface for mocking outbound requests.
  • Supports projects with multiple Workers.

Here’s an example of a unit-style and integration-style test using the integration:

import {
env,
SELF,
createExecutionContext,
waitOnExecutionContext,
} from "cloudflare:test";
import { it, expect } from "vitest";
import worker, { add } from "./index.mjs";
it("adds via function call", () => {
expect(add(1, 2)).toBe(3);
});
it("adds via request (unit style)", async () => {
const request = new Request("http://example.com/?a=1&b=2");
const ctx = createExecutionContext();
const response = await worker.fetch(request, env, ctx);
await waitOnExecutionContext(ctx);
expect(await response.text()).toBe("3");
});
it("adds via request (integration style)", async () => {
const response = await SELF.fetch("http://example.com/?a=1&b=2");
expect(await response.text()).toBe("3");
});