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.
You need:
- A Worker project with a Wrangler configuration file
- A Node.js test runner such as Vitest ↗
wranglerinstalled as a development dependency
Import createTestHarness() from wrangler. Point the test harness at your Worker configuration file.
import { createTestHarness } from "wrangler";
const server = createTestHarness({
workers: [{ configPath: "./wrangler.jsonc" }],
});import { createTestHarness } from "wrangler";
const server = createTestHarness({
workers: [{ configPath: "./wrangler.jsonc" }],
});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.
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();
});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();
});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.
import { test } from "vitest";
test("responds", async ({ expect }) => {
const response = await server.fetch("/");
expect(await response.text()).toBe("Hello World");
});import { test } from "vitest";
test("responds", async ({ expect }) => {
const response = await server.fetch("/");
expect(await response.text()).toBe("Hello World");
});