编写前端测试
- 作者仓库星标 184,730
- 作者仓库 AutoGPT
- 领域
- 人工智能
- 作者声明的智能体
- 未找到明确声明;不据此推断已兼容或已测试
- 静态检查
- 88 / 100 · 启发式扫描,不代表运行安全
- 运行环境证据
- 未执行;当前没有隔离运行测试证据
- 作者 / 版本 / 许可证
- @Significant-Gravitas · 未声明许可证
- 上下文用量评级
- 低消耗
- 接入复杂程度
- 即装即用
- 是否需要外部接口密钥
- 不需要
- 兼容的系统
- 未声明(默认跨平台)
- 运行环境要求
- 未检出明确要求
- 检测到的文件与系统行为
-
- 只读
- 允许写入 / 修改
- 网络行为
- 允许外网请求
- 安装命令数
- 无(仅作为资料)
需要注意: 未声明工具权限范围;实际权限由运行环境决定。
第 1 步:识别已更改的前端文件
另请阅读差异以了解发生了什么变化:
步骤 2:对变更进行分类并找到测试目标
对于每个更改的文件,确定:它是一个页面吗? (`page.tsx`) — 这些是主要测试目标 它是一个钩子吗? (`use*.ts`) — 通过使用它的页面/组件进行测试;避免直接 `renderHook()` 测试,除非它是具有独立业务逻辑的共享可重用钩子 它是一个组件吗? (`.tsx` in `components/`) — 通过父页面进行测试,除非它复杂到足以保证隔离它是一个助手吗? (`helpers.ts`, `utils.ts`) — 如果是纯逻辑则直接进行单元测试
第 3 步:检查现有测试
对于每个测试目标,检查测试是否已存在:注意哪些目标没有测试(需要新文件)与哪些目标有需要更新的测试。
第 4 步:识别使用的 API 端点
对于每个测试目标,查找使用了哪些 API 挂钩: 对于找到的每个 API 挂钩,找到相应的 MSW 处理程序: 列出您需要的每个 MSW 处理程序(200 表示顺利路径,4xx 表示错误路径)。
第五步:编写测试计划
在编写代码之前,以编号列表的形式输出计划:将该计划呈现给用户。等待确认后再继续。如果用户有反馈,调整计划。
第 6 步:编写测试
对于计划中的每个测试文件,请遵循以下约定:
第7步:运行并验证
编写所有测试后: 如果测试失败:仔细阅读错误输出 修复测试(不是源代码,除非存在真正的错误) 重新运行直到所有通过
# Write Frontend Tests
Analyze the current branch's frontend changes, plan integration tests, and write them.
## References
Before writing any tests, read the testing rules and conventions:
- `autogpt_platform/frontend/TESTING.md` — testing strategy, file locations, examples
- `autogpt_platform/frontend/src/tests/AGENTS.md` — detailed testing rules, MSW patterns, decision flowchart
- `autogpt_platform/frontend/src/tests/integrations/test-utils.tsx` — custom render with providers
- `autogpt_platform/frontend/src/tests/integrations/vitest.setup.tsx` — MSW server setup
## Step 1: Identify changed frontend files
```bash
BASE_BRANCH="${ARGUMENTS:-dev}"
cd autogpt_platform/frontend
# Get changed frontend files (excluding generated, config, and test files)
git diff "$BASE_BRANCH"...HEAD --name-only -- src/ \
| grep -v '__generated__' \
| grep -v '__tests__' \
| grep -v '\.test\.' \
| grep -v '\.stories\.' \
| grep -v '\.spec\.'
```
Also read the diff to understand what changed:
```bash
git diff "$BASE_BRANCH"...HEAD --stat -- src/
git diff "$BASE_BRANCH"...HEAD -- src/ | head -500
```
## Step 2: Categorize changes and find test targets
For each changed file, determine:
1. **Is it a page?** (`page.tsx`) — these are the primary test targets
2. **Is it a hook?** (`use*.ts`) — test via the page/component that uses it; avoid direct `renderHook()` tests unless it is a shared reusable hook with standalone business logic
3. **Is it a component?** (`.tsx` in `components/`) — test via the parent page unless it's complex enough to warrant isolation
4. **Is it a helper?** (`helpers.ts`, `utils.ts`) — unit test directly if pure logic
**Priority order:**
1. Pages with new/changed data fetching or user interactions
2. Components with complex internal logic (modals, forms, wizards)
3. Shared hooks with standalone business logic when UI-level coverage is impractical
4. Pure helper functions
Skip: styling-only changes, type-only changes, config changes.
## Step 3: Check for existing tests
For each test target, check if tests already exist:
```bash
# For a page at src/app/(platform)/library/page.tsx
ls src/app/\(platform\)/library/__tests__/ 2>/dev/null
# For a component at src/app/(platform)/library/components/AgentCard/AgentCard.tsx
ls src/app/\(platform\)/library/components/AgentCard/__tests__/ 2>/dev/null
```
Note which targets have no tests (need new files) vs which have tests that need updating.
## Step 4: Identify API endpoints used
For each test target, find which API hooks are used:
```bash
# Find generated API hook imports in the changed files
grep -rn 'from.*__generated__/endpoints' src/app/\(platform\)/library/
grep -rn 'use[A-Z].*V[12]' src/app/\(platform\)/library/
```
For each API hook found, locate the corresponding MSW handler:
```bash
# If the page uses useGetV2ListLibraryAgents, find its MSW handlers
grep -rn 'getGetV2ListLibraryAgents.*Handler' src/app/api/__generated__/endpoints/library/library.msw.ts
```
List every MSW handler you will need (200 for happy path, 4xx for error paths).
## Step 5: Write the test plan
Before writing code, output a plan as a numbered list:
```
Test plan for [branch name]:
1. src/app/(platform)/library/__tests__/main.test.tsx (NEW)
- Renders page with agent list (MSW 200)
- Shows loading state
- Shows error state (MSW 422)
- Handles empty agent list
2. src/app/(platform)/library/__tests__/search.test.tsx (NEW)
- Filters agents by search query
- Shows no results message
- Clears search
3. src/app/(platform)/library/components/AgentCard/__tests__/AgentCard.test.tsx (UPDATE)
- Add test for new "duplicate" action
```
Present this plan to the user. Wait for confirmation before proceeding. If the user has feedback, adjust the plan.
## Step 6: Write the tests
For each test file in the plan, follow these conventions:
### File structure
```tsx
import { render, screen, waitFor } from "@/tests/integrations/test-utils";
import { server } from "@/mocks/mock-server";
// Import MSW handlers for endpoints the page uses
import {
getGetV2ListLibraryAgentsMockHandler200,
getGetV2ListLibraryAgentsMockHandler422,
} from "@/app/api/__generated__/endpoints/library/library.msw";
// Import the component under test
import LibraryPage from "../page";
describe("LibraryPage", () => {
test("renders agent list from API", async () => {
server.use(getGetV2ListLibraryAgentsMockHandler200());
render(<LibraryPage />);
expect(await screen.findByText(/my agents/i)).toBeDefined();
});
test("shows error state on API failure", async () => {
server.use(getGetV2ListLibraryAgentsMockHandler422());
render(<LibraryPage />);
expect(await screen.findByText(/error/i)).toBeDefined();
});
});
```
### Rules
- Use `render()` from `@/tests/integrations/test-utils` (NOT from `@testing-library/react` directly)
- Use `server.use()` to set up MSW handlers BEFORE rendering
- Use `findBy*` (async) for elements that appear after data fetching — NOT `getBy*`
- Use `getBy*` only for elements that are immediately present in the DOM
- Use `screen` queries — do NOT destructure from `render()`
- Use `waitFor` when asserting side effects or state changes after interactions
- Import `fireEvent` or `userEvent` from the test-utils for interactions
- Do NOT mock internal hooks or functions — mock at the API boundary via MSW
- Prefer Orval-generated MSW handlers and response builders over hand-built API response objects
- Do NOT use `act()` manually — `render` and `fireEvent` handle it
- Keep tests focused: one behavior per test
- Use descriptive test names that read like sentences
### Test location
```
# For pages: __tests__/ next to page.tsx
src/app/(platform)/library/__tests__/main.test.tsx
# For complex standalone components: __tests__/ inside component folder
src/app/(platform)/library/components/AgentCard/__tests__/AgentCard.test.tsx
# For pure helpers: co-located .test.ts
src/app/(platform)/library/helpers.test.ts
```
### Custom MSW overrides
When the auto-generated faker data is not enough, override with specific data:
```tsx
import { http, HttpResponse } from "msw";
server.use(
http.get("http://localhost:3000/api/proxy/api/v2/library/agents", () => {
return HttpResponse.json({
agents: [{ id: "1", name: "Test Agent", description: "A test agent" }],
pagination: { total_items: 1, total_pages: 1, page: 1, page_size: 10 },
});
}),
);
```
Use the proxy URL pattern: `http://localhost:3000/api/proxy/api/v{version}/{path}` — this matches the MSW base URL configured in `orval.config.ts`.
## Step 7: Run and verify
After writing all tests:
```bash
cd autogpt_platform/frontend
pnpm test:unit --reporter=verbose
```
If tests fail:
1. Read the error output carefully
2. Fix the test (not the source code, unless there is a genuine bug)
3. Re-run until all pass
Then run the full checks:
```bash
pnpm format
pnpm lint
pnpm types
```
章节与文件索引
按说明文件中的顺序排列。
参考文献
第 1 步:识别已更改的前端文件
步骤 2:对变更进行分类并找到测试目标
第 3 步:检查现有测试
第 4 步:识别使用的 API 端点
文件/命令 -> autogpt_platform/frontend/TESTING.md · autogpt_platform/frontend/src/tests/AGENTS.md · autogpt_platform/frontend/src/tests/integrations/test-utils.tsx · autogpt_platform/frontend/src/tests/integrations/vitest.setup.tsx · page.tsx · use*.ts · renderHook() · .tsx
内容校验值 -> bf11dcb458e0
当前原文的自动摘译,尚未人工审校。
参考文献
在编写任何测试之前,请阅读测试规则和约定:
autogpt_platform/frontend/TESTING.md— 测试策略、文件位置、示例autogpt_platform/frontend/src/tests/AGENTS.md— 详细的测试规则、MSW 模式、决策流程图autogpt_platform/frontend/src/tests/integrations/test-utils.tsx— 使用提供程序进行自定义渲染autogpt_platform/frontend/src/tests/integrations/vitest.setup.tsx— MSW 服务器设置步骤 2:对变更进行分类并找到测试目标
对于每个更改的文件,确定:它是一个页面吗? (
page.tsx) — 这些是主要测试目标 它是一个钩子吗? (use*.ts) — 通过使用它的页面/组件进行测试;避免直接renderHook()测试,除非它是具有独立业务逻辑的共享可重用钩子 它是一个组件吗? (components/中的.tsx)-通过父页面进行测试,除非它复杂到足以保证隔离它是一个助手吗? (helpers.ts,utils.ts) — 如果是纯逻辑则直接进行单元测试