Skip to content

Get started

Last updated View as MarkdownAgent setup

This guide shows how to write a basic integration test for a Worker with createTestHarness(). The example uses Vitest as the test runner and exercises a Worker built with Wrangler.

Prerequisites

You need:

Create a test harness

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 harness 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 harness 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?