Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/test-and-check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ on:
permissions:
contents: read

env:
# We run `playwright install` manually instead
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: "1"

jobs:
add-to-project:
if: github.head_ref != 'changeset-release/main'
Expand Down
2 changes: 2 additions & 0 deletions fixtures/create-test-harness-example/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
test-results/
playwright-report/
58 changes: 58 additions & 0 deletions fixtures/create-test-harness-example/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Integration testing Workers with `createTestHarness()`

This fixture is the complete runnable example linked from the `createTestHarness()` docs. It shows how to test a realistic multi-Worker app's production build output from different test runners.

For the testing patterns demonstrated here, refer to the [`createTestHarness()` examples guide](https://developers.cloudflare.com/workers/testing/test-harness/examples/).

## Example app

The app has two Workers:

| Worker | Route | Role |
| ------------ | ---------------------- | ----------------------------------------------------------------------------- |
| `web-worker` | `example.com/*` | Handles user-facing routes and calls the API Worker over a service binding. |
| `api-worker` | `api.example.com/v1/*` | Fetches upstream user data, caches it in KV, and generates scheduled reports. |

## What this fixture covers

- Setup [Vitest](https://vitest.dev/) against Workers developed with Wrangler.
- Setup [Playwright](https://playwright.dev/) against Workers built by the Cloudflare Vite plugin.
- Route dispatch across multiple Workers.
- Direct Worker calls with `server.getWorker(name)`.
- Scheduled handler dispatch.
- Outbound request mocking with MSW.
- Local storage reset between tests.
- Debug output with `server.debug()`.
- Runtime log assertions with `server.getLogs()` and `server.clearLogs()`.

## Run this example

To build the packages, run:

```sh
pnpm build --filter @fixture/create-test-harness-example
```

Then run the tests with:

```sh
pnpm --filter @fixture/create-test-harness-example test:vitest
pnpm --filter @fixture/create-test-harness-example test:playwright
```

## Files

| File | Purpose |
| ---------------------------------------------------------- | ------------------------------------------- |
| [`tests/vitest.test.ts`](tests/vitest.test.ts) | Example for testing with Vitest. |
| [`tests/playwright.test.ts`](tests/playwright.test.ts) | Example for testing with Playwright. |
| [`vite.config.ts`](vite.config.ts) | Builds Vite-generated Worker configs. |
| [`workers/web/index.ts`](workers/web/index.ts) | User-facing Worker. |
| [`workers/web/wrangler.jsonc`](workers/web/wrangler.jsonc) | Web Worker config. |
| [`workers/api/index.ts`](workers/api/index.ts) | API Worker with KV and scheduled job logic. |
| [`workers/api/wrangler.jsonc`](workers/api/wrangler.jsonc) | API Worker config. |

## Related docs

- [`createTestHarness()` guide](https://developers.cloudflare.com/workers/testing/test-harness/)
- [`createTestHarness()` API reference](https://developers.cloudflare.com/workers/wrangler/api/#createtestharness)
32 changes: 32 additions & 0 deletions fixtures/create-test-harness-example/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "@fixture/create-test-harness-example",
"private": true,
"description": "Integration tests with the createTestHarness() API",
"type": "module",
"scripts": {
"check:type": "tsc",
"build": "vite build",
"playwright:install": "pnpm playwright install chromium",
"pretest:ci": "pnpm playwright:install",
"pretest:playwright": "pnpm playwright:install",
"test:playwright": "playwright test",
"test:vitest": "vitest run",
"test:ci": "vitest run && playwright test",
"type:tests": "tsc -p ./tests/tsconfig.json"
},
"devDependencies": {
"@cloudflare/vite-plugin": "workspace:*",
"@cloudflare/workers-tsconfig": "workspace:*",
"@cloudflare/workers-types": "catalog:default",
"@playwright/test": "catalog:default",
Comment thread
edmundhung marked this conversation as resolved.
"@types/node": "catalog:default",
"msw": "catalog:default",
"typescript": "catalog:default",
"vite": "catalog:default",
"vitest": "catalog:default",
"wrangler": "workspace:*"
},
"volta": {
"extends": "../../package.json"
}
}
9 changes: 9 additions & 0 deletions fixtures/create-test-harness-example/playwright.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { defineConfig } from "@playwright/test";

export default defineConfig({
testDir: "./tests",
testMatch: "playwright.test.ts",
use: {
browserName: "chromium",
},
});
105 changes: 105 additions & 0 deletions fixtures/create-test-harness-example/tests/playwright.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { test as base, expect } from "@playwright/test";
import { http, HttpResponse } from "msw";
import { setupServer, type SetupServerApi } from "msw/node";
import { createTestHarness, type TestHarness } from "wrangler";

type TestFixtures = {
reset: void;
};

type WorkerFixtures = {
network: SetupServerApi;
server: TestHarness;
};

const test = base.extend<TestFixtures, WorkerFixtures>({
network: [
async ({}, use) => {
const network = setupServer();
network.listen({ onUnhandledRequest: "error" });

await use(network);

network.close();
},
{ scope: "worker" },
],

server: [
async ({}, use) => {
const server = createTestHarness({
workers: [
// Playwright tests run against the Vite build output.
{ configPath: "./dist/web_worker/wrangler.json" },
{ configPath: "./dist/api_worker/wrangler.json" },
],
});

await server.listen();

await use(server);

await server.close();
},
{ scope: "worker" },
],

baseURL: async ({ server }, use) => {
const { url } = await server.listen();
await use(url.href);
},

reset: [
async ({ network, server }, use, testInfo) => {
await use();

if (testInfo.status !== testInfo.expectedStatus) {
server.debug();
}

network.resetHandlers();
await server.reset();
},
{ auto: true },
],
});

test.describe("createTestHarness: Playwright setup", () => {
test("renders a user profile", async ({ page, network }) => {
network.use(
http.get("http://identity.example.com/profile/:id", ({ params }) => {
return HttpResponse.json({ id: params.id, name: "Ada" });
})
);

await page.goto("/users/123");

await expect(page.getByText("Profile: Ada")).toBeVisible();
});

test("renders a report generated by a scheduled handler", async ({
page,
network,
server,
}) => {
network.use(
http.get("http://identity.example.com/profile/:id", ({ params }) => {
return HttpResponse.json({ id: params.id, name: "Ada" });
})
);

const apiWorker = server.getWorker("api-worker");
await apiWorker.fetch("/v1/users/123");
await apiWorker.fetch("/v1/users/456");
await apiWorker.scheduled({
cron: "0 0 * * *",
scheduledTime: new Date("2026-05-29T00:00:00.000Z"),
});

await page.goto("/reports/2026-05-29");

await expect(
page.getByText("Daily report (2026-05-29): active users 123, 456")
).toBeVisible();
});
});
9 changes: 9 additions & 0 deletions fixtures/create-test-harness-example/tests/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "@cloudflare/workers-tsconfig/tsconfig.json",
"compilerOptions": {
"module": "esnext",
"types": ["node"]
},
"include": ["../playwright.config.ts", "**/*.ts"],
"exclude": []
}
114 changes: 114 additions & 0 deletions fixtures/create-test-harness-example/tests/vitest.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import { http, HttpResponse } from "msw";
import { setupServer } from "msw/node";
import { afterAll, afterEach, beforeAll, describe, test } from "vitest";
import { createTestHarness } from "wrangler";

// Point each worker to the Wrangler config you want to test.
const server = createTestHarness({
workers: [
{ configPath: "./workers/web/wrangler.jsonc" },
{ configPath: "./workers/api/wrangler.jsonc" },
],
});

// server.getWorker() would return the first Worker, but naming it makes it explicit.
const webWorker = server.getWorker("web-worker");
const apiWorker = server.getWorker("api-worker");

// Workers started by createTestHarness route outbound fetches to globalThis.fetch().
// You can use libraries like MSW to intercept those requests.
const network = setupServer();

describe("createTestHarness: Vitest setup", () => {
beforeAll(async () => {
network.listen({ onUnhandledRequest: "error" });
await server.listen();
});

afterAll(async () => {
network.close();
await server.close();
});

afterEach(async () => {
// Keep tests isolated while reusing the same running server.
network.resetHandlers();
await server.reset();
});

test("fetches the primary Worker with a relative URL", async ({ expect }) => {
// Relative URLs are dispatched to the primary Worker (the first one listed).
const response = await server.fetch("/");
expect(await response.text()).toBe("Hello World");
});

test("mocks outbound requests", async ({ expect }) => {
network.use(
http.get("http://identity.example.com/profile/:id", ({ params }) => {
return HttpResponse.json({ id: params.id, name: "Ada" });
})
);

const userResponse = await apiWorker.fetch("/v1/users/123");
expect(await userResponse.json()).toEqual({
id: "123",
name: "Ada",
});
});

test("dispatches requests using configured routes", async ({ expect }) => {
network.use(
http.get("http://identity.example.com/profile/:id", ({ params }) => {
return HttpResponse.json({ id: params.id, name: "Ada" });
})
);

// server.fetch() matches requests to workers based on routes.
const apiResponse = await server.fetch(
"http://api.example.com/v1/users/123"
);
expect(await apiResponse.json()).toEqual({
id: "123",
name: "Ada",
});

const webResponse = await server.fetch("http://example.com/users/123");
expect(await webResponse.text()).toBe("Profile: Ada");
});

test("runs scheduled jobs and stores the result", async ({ expect }) => {
network.use(
http.get("http://identity.example.com/profile/:id", ({ params }) => {
return HttpResponse.json({ id: params.id, name: "Ada" });
})
);

// Seed user data that the scheduled job will read to generate a report.
await apiWorker.fetch("/v1/users/123");
await apiWorker.fetch("/v1/users/456");

const initialResponse = await webWorker.fetch("/reports/2026-05-29");
expect(initialResponse.status).toBe(404);
expect(await initialResponse.text()).toBe("No report");

server.clearLogs();

expect(
await apiWorker.scheduled({
cron: "0 0 * * *",
scheduledTime: new Date("2026-05-29T00:00:00.000Z"),
})
).toEqual({ outcome: "ok", noRetry: false });
expect(server.getLogs()).toContainEqual(
expect.objectContaining({
level: "info",
message: "Generated daily report for 2026-05-29",
})
);

const webResponse = await webWorker.fetch("/reports/2026-05-29");
expect(await webResponse.text()).toBe(
"Daily report (2026-05-29): active users 123, 456"
);
});
});
17 changes: 17 additions & 0 deletions fixtures/create-test-harness-example/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"compilerOptions": {
"isolatedModules": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"moduleResolution": "bundler",
"resolveJsonModule": true,
"target": "esnext",
"strict": true,
"noEmit": true,
"types": ["@cloudflare/workers-types", "node"],
"lib": ["esnext"],
"skipLibCheck": true
},
"include": ["**/*.ts"],
"exclude": ["tests"]
}
9 changes: 9 additions & 0 deletions fixtures/create-test-harness-example/turbo.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"$schema": "http://turbo.build/schema.json",
"extends": ["//"],
"tasks": {
"build": {
"outputs": ["dist/**"]
}
}
}
13 changes: 13 additions & 0 deletions fixtures/create-test-harness-example/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { cloudflare } from "@cloudflare/vite-plugin";
import { defineConfig } from "vite";

export default defineConfig({
plugins: [
cloudflare({
configPath: "./workers/web/wrangler.jsonc",
auxiliaryWorkers: [{ configPath: "./workers/api/wrangler.jsonc" }],
inspectorPort: false,
persistState: false,
}),
],
});
Loading
Loading