因为 Agents 运行在 Cloudflare Workers 和 Durable Objects 上,所以可以使用与 Workers 和 Durable Objects 相同的工具和技术来测试它们。
在编写第一个测试之前,安装必要的包:
npm install vitest@~3.0.0 --save-dev --save-exactnpm install @cloudflare/vitest-pool-workers --save-dev
确保您的 vitest.config.js
文件与以下内容相同:
import { defineWorkersConfig } from "@cloudflare/vitest-pool-workers/config";
export default defineWorkersConfig({ test: { poolOptions: { workers: { wrangler: { configPath: "./wrangler.toml" }, }, }, },});
在 vitest.config.js
中添加 durableObjects
配置,包含您的 Agent 类的名称:
import { defineWorkersConfig } from "@cloudflare/vitest-pool-workers/config";
export default defineWorkersConfig({ test: { poolOptions: { workers: { main: "./src/index.ts", miniflare: { durableObjects: { NAME: "MyAgent", }, }, }, }, },});
测试使用 vitest
框架。您的 Agent 的基本测试套件可以验证您的 Agent 如何响应请求,但也可以对您的 Agent 的方法和状态进行单元测试。
import { env, createExecutionContext, waitOnExecutionContext, SELF,} from "cloudflare:test";import { describe, it, expect } from "vitest";import worker from "../src";import { Env } from "../src";
interface ProvidedEnv extends Env {}
describe("向我的 Agent 发出请求", () => { // 单元测试方法 it("响应状态", async () => { // 提供一个有效的 URL,您的 Worker 可以使用它来路由到您的 Agent // 如果您使用 routeAgentRequest,这将是 /agent/:agent/:name const request = new Request<unknown, IncomingRequestCfProperties>( "http://example.com/agent/my-agent/agent-123", ); const ctx = createExecutionContext(); const response = await worker.fetch(request, env, ctx); await waitOnExecutionContext(ctx); expect(await response.text()).toMatchObject({ hello: "from your agent" }); });
it("也响应状态", async () => { const request = new Request("http://example.com/agent/my-agent/agent-123"); const response = await SELF.fetch(request); expect(await response.text()).toMatchObject({ hello: "from your agent" }); });});
运行测试使用 vitest
CLI:
$ npm run test# 或直接运行 vitest$ npx vitest
MyAgent ✓ 应该返回问候语 (1 ms)
Test Files 1 passed (1)
查看测试文档 了解更多示例和测试配置。
您也可以使用 wrangler
CLI 在本地运行 Agent:
$ 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 相同的运行时,让您可以迭代 Agent 的代码并在不部署的情况下本地测试。
访问 wrangler dev
↗ 文档以查看 CLI 标志和配置选项。
- @2025 Cloudflare Ubitools
- Cf Repo