Skip to content

Get started

This guide shows how to write a basic integration test for a Worker, using Vitest as the test runner.

Prerequisites

You need:

npm i -D @cloudflare/test-server

You need:

Create a test server

The test server runs your project's Build Output, not its source, so build the project before every test run. For example, in package.json:

{
	"scripts": {
		"test": "cf build && vitest run"
	}
}

If you run Vitest in watch mode, run cf build again after you change the Worker.

Import createTestServer() from @cloudflare/test-server. Set projectDir to the project's root directory.

test/index.test.jsjs
import { createTestServer } from "@cloudflare/test-server";

const server = createTestServer({
	workers: [{ projectDir: "./" }],
});
test/index.test.tsts
import { createTestServer } from "@cloudflare/test-server";

const server = createTestServer({
	workers: [{ projectDir: "./" }],
});

Import createTestHarness() from wrangler. Point the test harness at your Worker configuration file.

test/index.test.jsjs
import { createTestHarness } from "wrangler";

const server = createTestHarness({
	workers: [{ configPath: "./wrangler.jsonc" }],
});
test/index.test.tsts
import { createTestHarness } from "wrangler";

const server = createTestHarness({
	workers: [{ configPath: "./wrangler.jsonc" }],
});

Manage the test server lifecycle

For simplicity, we will reuse a single server for the test suite and reset it after each test. You can also start a new server for each test if the tests do not share the same configuration.

test/index.test.jsjs
import { afterAll, afterEach, beforeAll } from "vitest";

beforeAll(async () => {
	// Start the server before all tests
	await server.listen();
});

afterEach(async () => {
	// Recreates storage and restores the original Worker options after each test
	await server.reset();
});

afterAll(async () => {
	// Close the server after all tests
	await server.close();
});
test/index.test.tsts
import { afterAll, afterEach, beforeAll } from "vitest";

beforeAll(async () => {
	// Start the server before all tests
	await server.listen();
});

afterEach(async () => {
	// Recreates storage and restores the original Worker options after each test
	await server.reset();
});

afterAll(async () => {
	// Close the server after all tests
	await server.close();
});

Write your first test

Use the helpers provided by the test server to interact with the Worker and assert its behavior. For example, you can call server.fetch() to send a request to the Worker and assert against its response.

test/index.test.jsjs
import { test } from "vitest";

test("responds", async ({ expect }) => {
	const response = await server.fetch("/");
	expect(await response.text()).toBe("Hello World");
});
test/index.test.tsts
import { test } from "vitest";

test("responds", async ({ expect }) => {
	const response = await server.fetch("/");
	expect(await response.text()).toBe("Hello World");
});

Was this helpful?