Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

設定

最終更新 Markdown で表示Agent セットアップ

Workers の Vitest 連携は、cloudflareTest() Vite プラグインで、通常の Vitest オプションに加えて設定を追加します。

設定例は次のとおりです。

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

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

API

次の API は @cloudflare/vitest-plugin パッケージからエクスポートされます。

cloudflareTest(options)

Vitest が正しいモジュール解決設定で Workers 連携を使うようにし、CloudflareTestOptions の型チェックを提供する Vite プラグインです。Vitest の defineConfig() と並べて、Vitest 設定の plugins 配列に追加します。

options を返す任意の async 関数も受け取れます。

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

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

buildPagesASSETSBinding(assetsPath)

@cloudflare/vitest-plugin/config からエクスポートされます。assetsPath 内のファイルを配信する Pages の ASSETS バインディングを作ります。createPagesEventContext()Pages Functions をテストする場合に必要です。完全な例は Pages レシピ を参照してください。

import path from "node:path";
import { buildPagesASSETSBinding, cloudflareTest } from "@cloudflare/vitest-plugin";
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-plugin/config からエクスポートされます。migrationsPath に保存された D1 マイグレーション をすべて読み、マイグレーション番号順で返します。各マイグレーションの内容は、個別の SQL クエリの配列に分割されます。テスト内または セットアップファイルapplyD1Migrations() を呼び、マイグレーションを適用します。マイグレーションを使う例は D1 レシピ を参照してください。

import path from "node:path";
import { cloudflareTest, readD1Migrations } from "@cloudflare/vitest-plugin";
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 / コンテキストで実行する Worker のエントリポイントです。クラスが同じ Worker 内で定義されている場合、明示的な scriptName なしで Durable Objects を使うにはこのオプションが必要です。このファイルは Vite の変換を通り、TypeScript でも書けます。テスト内の import module from "<path-to-main>" は、exports と Durable Object バインディングで内部的に使われるものと同じ module インスタンスを返します。wrangler.configPath が定義されていてこのオプションがない場合は、その設定ファイルの main フィールドから読みます。
  • miniflare: SourcelessWorkerOptions & { workers?: WorkerOptions\[]; } optional

    • Wrangler 設定ファイル に通常書く情報(バインディング互換性日付互換性フラグ など)を渡します。WorkerOptions インターフェースは こちら で定義されています。エントリポイントは、Miniflare の scriptscriptPathmodules ではなく、上記の main オプションで設定します。

      • compatibility_date を指定しない場合、テストはローカルで利用可能な最新日付を使います。
    • プロジェクトが複数の Worker を使う場合、テストと同じ workerd プロセスで動き、バインドできる補助 Worker を設定できます。補助 Worker は workers 配列で設定し、通常の Miniflare WorkerOptions オブジェクトを入れます。main Worker と異なり、補助 Worker は次の制約があります。

      • TypeScript のエントリポイントは使えません。先に JavaScript へコンパイルしてください。これには wrangler deploy --dry-run --outdir dist コマンドを使えます。
      • 通常の Workers のモジュール解決セマンティクスを使います。詳細は Isolation and concurrency を参照してください。
      • cloudflare:test モジュールにはアクセスできません。
      • 特定の互換性日付やフラグは不要です。
      • Service Worker 構文 で書けます。
      • テストで定義したグローバルモックの影響を受けません。
  • wrangler: { configPath?: string; environment?: string; } optional

    • main互換性設定バインディング を読み込む Wrangler 設定ファイル のパスです。これらのオプションは上記の miniflare オプションとマージされ、miniflare の値が優先されます。たとえば Wrangler 設定で service という Worker への Service binding SERVICE を定義していても、miniflare オプションに serviceBindings: { SERVICE(request) { return new Response("body"); } } を含めると、テスト内の SERVICE へのリクエストはすべて body を返します。configPath.toml.json の両方を受け付けます。

    • environment オプションで、バインディングと変数を取得する Wrangler 環境 を指定できます。

inject による動的設定

cloudflareTest()async 関数を渡し、その関数で inject 関数を受け取れます。globalSetup スクリプトから注入された値に基づいて、miniflare 設定を定義できます。テスト実行時に初めて分かる動的な値を設定に使う場合に利用します。たとえば、グローバルセットアップスクリプトがランダムポートでアップストリームサーバーを起動することがあります。そのポートを provide() し、外部サービスバインディングや Hyperdrive の設定で inject() できます。この 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-plugin";
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"
>;

役に立ちましたか?