-
Notifications
You must be signed in to change notification settings - Fork 1.3k
chore: add create-test-harness-example fixture as recipes
#14278
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| test-results/ | ||
| playwright-report/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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", | ||
| "@types/node": "catalog:default", | ||
| "msw": "catalog:default", | ||
| "typescript": "catalog:default", | ||
| "vite": "catalog:default", | ||
| "vitest": "catalog:default", | ||
| "wrangler": "workspace:*" | ||
| }, | ||
| "volta": { | ||
| "extends": "../../package.json" | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
105
fixtures/create-test-harness-example/tests/playwright.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
114
fixtures/create-test-harness-example/tests/vitest.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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" | ||
| ); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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/**"] | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, | ||
| }), | ||
| ], | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.