Skip to content

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

エージェントのテスト

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

Agents は Cloudflare Workers と Durable Objects 上で動くため、Workers や Durable Objects と同じツールと手法でテストできます。

テストの作成と実行

セットアップ

最初のテストを書く前に、必要なパッケージをインストールします。

npm install vitest@^4.1.0 @cloudflare/vitest-plugin --save-dev

vitest.config.jscloudflareTest プラグインが設定されていることを確認します。

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

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

テストを書く

テストには vitest フレームワークを使います。エージェント向けの基本的なテストスイートでは、リクエストへの応答を検証できるほか、エージェントのメソッドと状態をユニットテストできます。

import { env, exports } from "cloudflare:workers";
import {
	createExecutionContext,
	waitOnExecutionContext,
} from "cloudflare:test";
import { describe, it, expect } from "vitest";
import worker from "../src";
import { Env } from "../src";

interface ProvidedEnv extends Env {}

describe("make a request to my Agent", () => {
	// Unit testing approach
	it("responds with state", async () => {
		// Provide a valid URL that your Worker can use to route to your Agent
		// If you are using routeAgentRequest, this will be /agents/:agent/:name
		const request = new Request<unknown, IncomingRequestCfProperties>(
			"http://example.com/agents/my-agent/agent-123",
		);
		const ctx = createExecutionContext();
		const response = await worker.fetch(request, env, ctx);
		await waitOnExecutionContext(ctx);
		expect(await response.json()).toEqual({ hello: "from your agent" });
	});

	it("also responds with state", async () => {
		const request = new Request("http://example.com/agents/my-agent/agent-123");
		const response = await exports.default.fetch(request);
		expect(await response.json()).toEqual({ hello: "from your agent" });
	});
});

テストを実行する

テストの実行には vitest CLI を使います。

npm run test
# or run vitest directly
npx vitest
  MyAgent
    ✓ should return a greeting (1 ms)

Test Files  1 passed (1)

追加の例とテスト設定は、テストのドキュメント を参照してください。

エージェントをローカルで実行する

wrangler CLI でエージェントをローカル実行することもできます。

npx wrangler dev
Your Worker and resources are simulated locally via Miniflare. For more information, see: https://developers.cloudflare.com/workers/testing/local-development.

Your worker has access to the following bindings:
- Durable Objects:
  - MyAgent: MyAgent
  Starting local server...
[wrangler:inf] Ready on http://localhost:53645

これで、Cloudflare Workers と同じランタイムを使うローカル開発サーバーが起動します。デプロイせずに、エージェントのコードを繰り返し修正してローカルで確認できます。

CLI フラグと設定オプションは wrangler dev のドキュメントを参照してください。

役に立ちましたか?