跳转到内容
搜索文档

配置

最后更新 查看 MarkdownAgent 设置

Workers Vitest 集成通过 cloudflareTest() Vite 插件,在 Vitest 常规选项之上提供额外配置。

示例配置如下:

import { cloudflareTest } from "@cloudflare/vitest-pool-workers";
import { defineConfig } from "vitest/config";

export default defineConfig({
	plugins: [
		cloudflareTest({
			wrangler: {
				configPath: "./wrangler.jsonc",
			},
		}),
	],
});

API

以下 API 从 @cloudflare/vitest-pool-workers 包导出。

cloudflareTest(options)

一个 Vite 插件,用于配置 Vitest 以正确的模块解析设置使用 Workers 集成,并为 CloudflareTestOptions 提供类型检查。请将其与 Vitest 的 defineConfig() 一起添加到 Vitest 配置的 plugins 数组中。

它也可以接受一个可选的 async 函数,该函数返回 options

import { cloudflareTest } from "@cloudflare/vitest-pool-workers";
import { defineConfig } from "vitest/config";

export default defineConfig({
	plugins: [
		cloudflareTest({
			// Refer to CloudflareTestOptions...
		}),
	],
});

buildPagesASSETSBinding(assetsPath)

@cloudflare/vitest-pool-workers/config 导出。创建一个 Pages ASSETS 绑定(binding),用于提供 assetsPath 内的文件。如果你使用 createPagesEventContext() 测试 Pages Functions,则需要此绑定。完整示例请参阅 Pages 示例

import path from "node:path";
import { buildPagesASSETSBinding, cloudflareTest } from "@cloudflare/vitest-pool-workers";
import { defineConfig } from "vitest/config";

export default defineConfig({
	plugins: [
		cloudflareTest(async () => {
			const assetsPath = path.join(__dirname, "public");

			return {
				miniflare: {
					serviceBindings: {
						ASSETS: await buildPagesASSETSBinding(assetsPath),
					},
				},
			};
		}),
	],
});

readD1Migrations(migrationsPath)

@cloudflare/vitest-pool-workers/config 导出。读取存储在 migrationsPath 的所有 D1 迁移,并按迁移编号排序返回。每个迁移的内容会被拆分为单独的 SQL 查询数组。在测试或 setup 文件 中调用 applyD1Migrations() 函数以应用迁移。使用迁移的示例项目请参阅 D1 示例

import path from "node:path";
import { cloudflareTest, readD1Migrations } from "@cloudflare/vitest-pool-workers";
import { defineConfig } from "vitest/config";

export default defineConfig({
	plugins: [
		cloudflareTest(async () => {
			const migrationsPath = path.join(__dirname, "migrations");
			const migrations = await readD1Migrations(migrationsPath);

			return {
				miniflare: {
					// Add a test-only binding for migrations, so we can apply them in a setup file
					bindings: { TEST_MIGRATIONS: migrations },
				},
			};
		}),
	],
	test: {
		setupFiles: ["./test/apply-migrations.ts"],
	},
});

CloudflareTestOptions

直接传递给 cloudflareTest() 的选项。

  • main: string optional

    • 与测试在同一 isolate/context 中运行的 Worker 入口点。如果类定义在同一 Worker 中且没有显式 scriptName,则使用 Durable Objects 时必须设置此选项。该文件会经过 Vite 转换,可以是 TypeScript。注意,在测试中使用 import module from "<path-to-main>" 所得到的 module 实例,与内部用于 exports 和 Durable Object 绑定的实例完全相同。如果定义了 wrangler.configPath 且未设置此选项,将从该配置文件的 main 字段读取。
  • miniflare: SourcelessWorkerOptions & { workers?: WorkerOptions\[]; } optional

    • 用于提供通常存储在 Wrangler 配置文件 中的配置信息,例如绑定兼容性日期兼容性标志WorkerOptions 接口定义见此处。请使用上面的 main 选项配置入口点,而不是 Miniflare 的 scriptscriptPathmodules 选项。

      • 如果未提供 compatibility_date,测试将使用本地可用的最新日期。
    • 如果项目使用多个 Worker,可以配置在测试的同一 workerd 进程中运行并可绑定的辅助 Worker。辅助 Worker 通过 workers 数组配置,其中包含常规 Miniflare WorkerOptions 对象。注意,与 main Worker 不同,辅助 Worker:

  • wrangler: { configPath?: string; environment?: string; } optional

    • 指向 Wrangler 配置文件的路径,用于加载 main兼容性设置绑定。这些选项将与上面的 miniflare 选项合并,miniflare 的值优先。例如,如果 Wrangler 配置定义了名为 SERVICE服务绑定,指向名为 service 的 Worker,但你在 miniflare 选项中包含了 serviceBindings: { SERVICE(request) { return new Response("body"); } },则测试中所有对 SERVICE 的请求都会返回 body。注意 configPath 同时接受 .toml.json 文件。

    • environment 选项可用于指定要读取绑定和变量的 Wrangler 环境

使用 inject 的动态配置

你可以向 cloudflareTest() 传递一个接收 inject 函数的 async 函数。这样可以根据 globalSetup 脚本注入的值来定义 miniflare 配置。如果配置中有动态生成且仅在测试运行时才确定的值,请使用此方式。例如,全局 setup 脚本可能在随机端口上启动上游服务器。该端口可以通过 provide() 提供,然后在配置中通过 inject() 注入,用于外部服务绑定或 Hyperdrive。使用 provide/inject 方式的示例项目请参阅 Hyperdrive 示例

示例说明

// env.d.ts
declare module "vitest" {
	interface ProvidedContext {
		port: number;
	}
}

// global-setup.ts
import type { GlobalSetupContext } from "vitest/node";
export default function ({ provide }: GlobalSetupContext) {
	// Runs inside Node.js, could start server here...
	provide("port", 1337);
	return () => {
		/* ...then teardown here */
	};
}

// vitest.config.ts
import { cloudflareTest } from "@cloudflare/vitest-pool-workers";
import { defineConfig } from "vitest/config";

export default defineConfig({
	plugins: [
		cloudflareTest(({ inject }) => ({
			miniflare: {
				hyperdrives: {
					DATABASE: `postgres://user:[email protected]:${inject("port")}/db`,
				},
			},
		})),
	],
	test: {
		globalSetup: ["./global-setup.ts"],
	},
});

SourcelessWorkerOptions

不含 scriptscriptPathmodules 属性的 Sourceless WorkerOptions 类型。更多详情请参阅 Miniflare WorkerOptions 类型。

type SourcelessWorkerOptions = Omit<
	WorkerOptions,
	"script" | "scriptPath" | "modules" | "modulesRoot"
>;

这篇文档对您有帮助吗?