由于 Agent 在 Cloudflare Workers 和 Durable Objects 上运行,可使用与 Workers 和 Durable Objects 相同的工具和技术进行测试。
编写第一个测试前,安装必要的包:
npm install vitest@^4.1.0 @cloudflare/vitest-pool-workers --save-dev确保 vitest.config.js 配置了 cloudflareTest 插件:
import { cloudflareTest } from "@cloudflare/vitest-pool-workers";
import { defineConfig } from "vitest/config";
export default defineConfig({
plugins: [
cloudflareTest({
wrangler: { configPath: "./wrangler.jsonc" },
}),
],
});测试使用 vitest 框架。Agent 的基本测试套件可验证 Agent 如何响应请求,也可对 Agent 方法和状态进行单元测试。
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 本地运行 Agent:
npx wrangler devYour 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 代码并在不部署的情况下本地测试。
有关 CLI 标志和配置选项,请参阅 wrangler dev 文档。