AGENT SKILL

自动化测试套件设计与实现

testing

设计并实现全面的测试套件。涵盖单元测试、集成测试、使用 Playwright 的 E2E 测试、API 测试、mock 策略、测试数据工厂、TDD 工作流、快照测试、覆盖率目标以及 CI 集成。适用于编写测试、设计测试架构或排查测试失败。

适用职业测试工程师
License 许可
MIT
最近更新
2026-09-14
Stars
★ 68
Forks
15

01 前言 Front Matter

name
testing
description
Design and implement comprehensive test suites. Covers unit testing, integration testing, E2E testing with Playwright, API testing, mocking strategies, test data factories, TDD workflow, snapshot testing, coverage targets, and CI integration. Use when writing tests, designing test architecture, or debugging test failures.

02 资源文件 1

03 SKILL.md 正文

Advanced Testing

Test Architecture

Test Pyramid

        /  E2E  \        ← Few: critical user flows only
       /----------\
      / Integration \    ← Medium: API routes, DB queries
     /----------------\
    /    Unit Tests     \ ← Many: business logic, utils, transforms

File Organization

src/
├── services/
│   ├── user-service.ts
│   └── user-service.test.ts      ← Colocated unit tests
├── routes/
│   ├── auth.ts
│   └── auth.integration.test.ts  ← Integration tests
└── __tests__/
    └── e2e/
        └── auth-flow.spec.ts     ← E2E tests

Unit Testing (Vitest / Jest)

Test Data Factory

function createUser(overrides: Partial<User> = {}): User {
  return {
    id: crypto.randomUUID(),
    email: `user-${Date.now()}@test.com`,
    name: "Test User",
    role: "USER",
    createdAt: new Date(),
    updatedAt: new Date(),
    ...overrides,
  };
}

function createPost(overrides: Partial<Post> = {}): Post {
  return {
    id: crypto.randomUUID(),
    title: "Test Post",
    content: "Test content for testing purposes.",
    published: false,
    authorId: crypto.randomUUID(),
    createdAt: new Date(),
    ...overrides,
  };
}

AAA Pattern with Edge Cases

describe("UserService", () => {
  describe("createUser", () => {
    it("creates user with valid input", async () => {
      const input = { email: "valid@test.com", name: "Valid User" };
      const user = await userService.create(input);
      expect(user.id).toBeDefined();
      expect(user.email).toBe("valid@test.com");
    });

    it("throws on duplicate email", async () => {
      await userService.create({ email: "dup@test.com", name: "First" });
      await expect(userService.create({ email: "dup@test.com", name: "Second" }))
        .rejects.toThrow("Email already exists");
    });

    it("trims and lowercases email", async () => {
      const user = await userService.create({ email: "  UPPER@Test.COM  ", name: "User" });
      expect(user.email).toBe("upper@test.com");
    });

    it("rejects empty name", async () => {
      await expect(userService.create({ email: "a@b.com", name: "" }))
        .rejects.toThrow();
    });
  });
});

Mocking Patterns

// Mock external service
vi.mock("../lib/email", () => ({
  sendEmail: vi.fn().mockResolvedValue({ success: true }),
}));

// Mock with implementation
const mockFetch = vi.fn().mockImplementation((url: string) => {
  if (url.includes("/users/123")) {
    return Promise.resolve({ ok: true, json: () => Promise.resolve({ id: "123", name: "Test" }) });
  }
  return Promise.resolve({ ok: false, status: 404 });
});

// Spy on method
const logSpy = vi.spyOn(logger, "error");
await processOrder(invalidOrder);
expect(logSpy).toHaveBeenCalledWith("Order processing failed", expect.any(Object));

API Integration Testing

import { describe, it, expect, beforeAll, afterAll } from "vitest";
import request from "supertest";
import { app } from "../app";

describe("POST /api/auth/register", () => {
  it("returns 201 with valid registration", async () => {
    const res = await request(app)
      .post("/api/auth/register")
      .send({ email: "new@test.com", password: "SecurePass123", name: "New User" })
      .expect(201);

    expect(res.body.data.user.email).toBe("new@test.com");
    expect(res.body.data.token).toBeDefined();
    expect(res.body.data.user.password).toBeUndefined(); // Never expose
  });

  it("returns 400 for weak password", async () => {
    await request(app)
      .post("/api/auth/register")
      .send({ email: "test@test.com", password: "weak", name: "User" })
      .expect(400);
  });

  it("returns 409 for duplicate email", async () => {
    await request(app).post("/api/auth/register")
      .send({ email: "existing@test.com", password: "Pass123!", name: "User" });
    await request(app).post("/api/auth/register")
      .send({ email: "existing@test.com", password: "Pass456!", name: "User2" })
      .expect(409);
  });
});

E2E Testing (Playwright)

import { test, expect } from "@playwright/test";

test.describe("Authentication Flow", () => {
  test("user can register, login, and access dashboard", async ({ page }) => {
    await page.goto("/register");
    await page.getByLabel("Email").fill("e2e@test.com");
    await page.getByLabel("Password").fill("SecurePass123!");
    await page.getByLabel("Name").fill("E2E User");
    await page.getByRole("button", { name: "Register" }).click();

    await expect(page).toHaveURL("/dashboard");
    await expect(page.getByText("Welcome, E2E User")).toBeVisible();
  });

  test("shows error on invalid credentials", async ({ page }) => {
    await page.goto("/login");
    await page.getByLabel("Email").fill("wrong@test.com");
    await page.getByLabel("Password").fill("wrongpass");
    await page.getByRole("button", { name: "Sign in" }).click();

    await expect(page.getByText("Invalid credentials")).toBeVisible();
    await expect(page).toHaveURL("/login");
  });
});

Coverage & CI

Coverage Targets

Layer Target Strategy
Business logic 90%+ Unit tests
API routes 80%+ Integration tests
UI components 70%+ Component tests
E2E flows Critical paths Playwright

CI Configuration

test:
  runs-on: ubuntu-latest
  steps:
    - uses: actions/checkout@v4
    - uses: actions/setup-node@v4
    - run: npm ci
    - run: npm run test -- --coverage
    - run: npx playwright install --with-deps
    - run: npm run test:e2e

Rules

  • Test behavior, not implementation details
  • NEVER hardcode values to make tests pass — fix the code
  • Use factories for test data — never raw objects
  • Mock external dependencies — never real APIs in unit tests
  • One concept per test — descriptive test names
  • Clean up test data in afterEach / afterAll

04 同仓库更多 Skills

RaheesAhmed
RaheesAhmed/SajiCode

演示测试技能

demo-skill

用于测试的演示插件技能。

普通用户示例与演示技能
★ 68
RaheesAhmed
RaheesAhmed/SajiCode

智能体技能开发

write-a-skill

创建新的智能体技能,具备合理的结构、渐进式披露(progressive disclosure)机制和配套捆绑资源。当用户想要创建、编写或构建新技能时使用。

AI 工程师插件与技能管理
★ 68
RaheesAhmed
RaheesAhmed/SajiCode

网络调研与数据提取

web-research

深度网络研究与数据提取技能。通过获取 URL、阅读文档、爬取 API 文档、评估 npm/pypi 包、比较技术,并将研究发现综合为可操作的建议,系统地研究任意主题。适用于研究库、框架、API、解决方案,或任何需要网络调查的主题。

知识工作者网页搜索与信息研究
★ 68
RaheesAhmed
RaheesAhmed/SajiCode

工程开发工作流与质量规范

superpowers

核心工程工作流,在每一项任务中都会激活。强制执行系统化的“先计划后编码”方法论、多文件重构安全、依赖感知的变更、预检验证以及零占位符质量标准。在所有编码任务中主动(PROACTIVELY)使用。

软件开发工程师工程实践准则
★ 68
RaheesAhmed
RaheesAhmed/SajiCode

CSS样式系统设计与实现

styling

使用 Tailwind CSS、原生 CSS 或 CSS-in-JS 实现生产级样式系统。涵盖 CSS 架构(BEM、utility-first、模块化)、设计令牌、响应式模式、动画系统、暗黑模式、容器查询、打印样式以及性能优化。适用于实现设计或构建 CSS 架构。

软件开发工程师前端开发与界面实现
★ 68
RaheesAhmed
RaheesAhmed/SajiCode

shadcn/ui 界面构建

shadcn-ui

使用 shadcn/ui 组件、Radix 原语和 Tailwind CSS 构建高品质界面。涵盖安装、组件定制、主题、暗黑模式、使用 react-hook-form + Zod 的表单模式、带排序/过滤/分页的数据表格、命令面板、toast 模式以及可组合的组件架构。适用于使用 shadcn/ui 构建 UI 时使用。

软件开发工程师前端开发与界面实现
★ 68