选项
首页首页 Skill 浏览器自动化 frontend-testing-best-practices

frontend-testing-best-practices

sergiodxa/agent-skills sergiodxa/agent-skills

前端测试的最佳实践。强调端到端测试(E2E)优先于单元测试,尽量减少模拟,并侧重于测试行为而非实现细节。在编写测试或审查测试代码时可参考这些原则。

...展开全部
53
更新时间 2026-07-07

简介frontend-testing-best-practices

frontend-testing-best-practices 技能提供了编写高效且易于维护的前端应用程序测试的全面指南。它针对测试存在脆弱、难以维护以及因关注实现细节而非用户行为而产生虚假信心等常见问题,并致力于解决这些问题。 该技能强调一种测试理念:优先采用端到端(E2E)测试而非单元测试,尽量减少模拟,并侧重于测试行为而非实现细节。

该技能包含 6 条核心规则,分为三大类别:测试策略(关键级别)、端到端测试(高优先级)和单元测试(中优先级)。 关键能力包括:何时编写端到端测试而非单元测试的指导;如何将端到端测试结构化放置在正确的目录中;在 Playwright 测试中使用可访问选择器的最佳实践;避免编写 React 组件单元测试;以及保持模拟的简洁性。这些规则通过实用的代码示例对比优劣做法,使指导原则能够立即付诸实践。

本技能非常适合从事 Web 应用开发的前端开发者,他们需要做出测试决策、编写新测试或审查测试代码。 对于使用 Playwright 进行端到端测试、并采用 React 开发 UI 组件的团队而言,该技能尤为宝贵。在决定编写何种类型的测试、实现新的测试覆盖率、重构现有测试或对测试文件进行代码审查时,均可运用此技能。这些指南有助于团队避免常见的测试反模式,并构建出能真正确保应用程序行为可靠的测试套件。

常见问题

何时应编写单元测试,何时应编写端到端测试?

在大多数情况下,应默认采用端到端测试。仅对没有依赖项且执行孤立逻辑(如数据格式化或计算)的纯函数编写单元测试。如果要测试涉及 React 组件、API 调用或用户交互的内容,请改写端到端测试。

本技能假设使用哪种测试框架?

本技能使用 Playwright 进行端到端测试示例,并参考 MSW(Mock Service Worker)进行 API 模拟。React 组件示例建议使用 JavaScript/TypeScript 前端栈,但核心原则适用于任何前端框架。

测试中使用多少个模拟对象算太多?

如果单个测试中需要 3 个或更多模拟对象,这表明应改写端到端测试。简单的模拟(例如针对 API 端点的单个 MSW 处理程序)是可以接受的,但复杂的模拟配置则表明你应该测试真实的集成系统。

端到端测试应放置在项目的哪个位置?

端到端测试应放置在项目根目录下的 e2e/tests/ 目录中,而非 frontend/ 目录内。这样既能将其与单元测试区分开来,也能明确表明它们是针对整个系统进行的测试。

在 Playwright 测试中应采用哪种选择器策略?

请遵循以下优先级:优先使用基于角色的选择器(getByRole),其次是基于标签的选择器(getByLabel),然后是文本内容,最后仅在没有可访问的选择器时才使用测试 ID(getByTestId)。请避免使用 CSS 选择器,因为它们不稳定,且无法反映用户与应用程序的交互方式。

在 GitHub 上查看

Testing Best Practices

Guidelines for writing effective, maintainable tests that provide real confidence. Contains 6 rules focused on preferring E2E tests, minimizing mocking, and testing behavior over implementation.

Core Philosophy

  1. Prefer E2E tests over unit tests - Test the whole system, not isolated pieces
  2. Minimize mocking - If you need complex mocks, write an E2E test instead
  3. Test behavior, not implementation - Test what users see and do
  4. Avoid testing React components directly - Test them through E2E

When to Apply

Reference these guidelines when:

  • Deciding what type of test to write
  • Writing new E2E or unit tests
  • Reviewing test code
  • Refactoring tests

Rules Summary

Testing Strategy (CRITICAL)

prefer-e2e-tests - @rules/prefer-e2e-tests.md

Default to E2E tests. Only write unit tests for pure functions.

// E2E test (PREFERRED) - tests real user flowtest("user can place an order", async ({ page }) => {  await createTestingAccount(page, { account_status: "active" });  await page.goto("/catalog");  await page.getByRole("heading", { name: "Example Item" }).click();  await page.getByRole("link", { name: "Buy" }).click();  // ... complete flow  await expect(page.getByAltText("Thank you")).toBeVisible();});// Unit test - ONLY for pure functionstest("formatCurrency formats with two decimals", () => {  expect(formatCurrency(1234.5)).toBe("$1,234.50");});

avoid-component-tests - @rules/avoid-component-tests.md

Don't unit test React components. Test them through E2E or not at all.

// BAD: Component unit testdescribe("OrderCard", () => {  test("renders amount", () => {    render(<OrderCard amount={100} />);    expect(screen.getByText("$100")).toBeInTheDocument();  });});// GOOD: E2E test covers the component naturallytest("order history shows orders", async ({ page }) => {  await page.goto("/orders");  await expect(page.getByText("$100")).toBeVisible();});

minimize-mocking - @rules/minimize-mocking.md

Keep mocks simple. If you need 3+ mocks, write an E2E test instead.

// BAD: Too many mocks = write E2E testvi.mock("~/lib/auth");vi.mock("~/lib/transactions");vi.mock("~/hooks/useAccount");// GOOD: Simple MSW mock for loader testmockServer.use(  http.get("/api/user", () => HttpResponse.json({ name: "John" })),);

E2E Tests (HIGH)

e2e-test-structure - @rules/e2e-test-structure.md

E2E tests go in e2e/tests/, not frontend/.

// e2e/tests/order.spec.tsimport { test, expect } from "@playwright/test";import { addAccountBalance, createTestingAccount } from "./utils";test.describe("Orders", () => {  test.beforeEach(async ({ page, context }) => {    await createTestingAccount(page, { account_status: "active" });    let cookies = await context.cookies();    let account_id = cookies.find((c) => c.name === "account_id").value;    await addAccountBalance({ account_id, amount: 10000, replaceBalance: true });  });  test("place order with default values", async ({ page }) => {    await page.goto("/catalog");    // ... user flow  });});

e2e-selectors - @rules/e2e-selectors.md

Use accessible selectors: role > label > text > testid.

// GOOD: Role-based (preferred)await page.getByRole("button", { name: "Submit" }).click();await page.getByRole("heading", { name: "Dashboard" });// GOOD: Label-basedawait page.getByLabel("Email").fill("[email protected]");// OK: Test ID when no accessible selector existsawait expect(page.getByTestId("balance")).toHaveText("$1,234");// BAD: CSS selectorsawait page.locator(".btn-primary").click();

Unit Tests (MEDIUM)

unit-test-structure - @rules/unit-test-structure.md

Unit tests for pure functions only. Co-locate with source files.

// app/utils/format.test.tsimport { describe, test, expect } from "vitest";import { formatCurrency } from "./format";describe("formatCurrency", () => {  test("formats positive amounts", () => {    expect(formatCurrency(1234.5)).toBe("$1,234.50");  });  test("handles zero", () => {    expect(formatCurrency(0)).toBe("$0.00");  });});

Key Files

  • e2e/tests/ - E2E tests (Playwright)
  • e2e/tests/utils.ts - E2E test utilities
  • vitest.config.ts - Unit test configuration
  • vitest.setup.ts - Global test setup with MSW
  • app/utils/test-utils.ts - Unit test utilities

安装 frontend-testing-best-practices

下载技能文件并将其解压到 .claude/skills/ 目录中。

下载ZIP

克隆仓库并复制技能文件到您的项目中。

git clone https://github.com/sergiodxa/agent-skills/blob/main/skills/frontend-testing-best-practices/SKILL.md # Copy SKILL.md to your .claude/skills/ directory

复制 复制
快速设置: 将技能文件夹复制到 .claude/skills/ 目录下,Claude 会自动检测并使用该技能

相关技能

playwright-cli
更新时间 2026-06-29
Playwright Browser Automation
更新时间 2026-06-29
playwright-generate-test
更新时间 2026-06-29
playwright-expert
更新时间 2026-06-29
OR