跳到正文
cccskills
免费在 GitHub 公开

test-driven

TDD methodology for production-quality tests. Write tests FIRST driven by PRD, Tech Spec, Implementation Plan. Covers minimal mocking, realistic test data, strong assertions, test independence.

中文简介正在准备中。当前显示原文说明。

查看安装方法

包含的文件(9)

  • SKILL.md8.6 KB
  • references/anti-patterns.md10.1 KB
  • references/gui-testing-mcp.md13.9 KB
  • references/integration-testing.md13.1 KB
  • references/review-checklist.md12.2 KB
  • references/test-data-factories.md13.3 KB
  • references/test-patterns.md10.6 KB
  • references/test-writing-guide.md12.2 KB
  • SKILL.extended.md20.3 KB

SKILL.md(原文)

安装前可以查看交给 AI 代理的指令内容。

Test-Driven Development Skill

Write tests FIRST, driven by project documents.

Critical: Document-Driven Testing

Before writing any test:

  1. Read latest PRD: docs/prd/[latest].md
  2. Read latest Tech Spec: docs/tech-spec/[latest].md
  3. Read Implementation Plan: docs/implementation-plan/[latest].md
  4. CONFIRM with user: "Is [filename] the current document?"

Test Pyramid

Layers listed top (fewest tests, slowest, highest business value) to bottom (most tests, fastest). MORE tests at bottom, FEWER at top.

LayerSourceLocationToolsSpeed
Cucumber (acceptance)PRD feature filesfeatures/Cucumber.jsSlow
GUI/E2E (visual, flows)Test plantests/e2e/DevTools MCPSlow
Integration (API, database)Tech spec APIstests/integration/Supertest, real DBMedium
Unit (functions, logic)Implementationtests/unit/Jest, VitestFast

Key Principle: Cucumber tests ARE your acceptance criteria. The .feature files from PRD (Phase 1) are your tests. Your job in Phase 4 is to implement the step definitions that make them pass — you do NOT write acceptance test specs in Phase 4, they already exist. Requirements = tests.

TDD Cycle

RED (Write failing test) -> GREEN (Make pass) -> REFACTOR (Clean up) -> REPEAT
PhaseActionRule
REDWrite failing testMUST fail first
GREENMinimal code to passNo extra features
REFACTORClean upTests still pass

BDD Test Execution (Cucumber)

Cucumber executes the acceptance criteria written during Phase 1 (PRD). Each .feature file in features/ becomes an executable test.

CommandWhen to UseWhat It Does
npm run cucumberLocal developmentRuns all features with progress bar
npm run cucumber:dryAfter writing featuresValidates Gherkin syntax, shows undefined steps
npm run test:bddBefore PRRuns all + generates HTML report
npm run test:smokeQuick checkRuns only @smoke tagged scenarios
npm run test:criticalRelease gateRuns only @critical scenarios

TDD with Cucumber

1. Write feature (Phase 1 - PRD)  → features/auth/login.feature
2. Run dry-run                    → npm run cucumber:dry → See undefined steps
3. Implement steps                → features/step-definitions/auth.steps.ts
4. Run tests                      → npm run cucumber → Should pass
5. Generate report                → npm run test:bdd → Review HTML report

Tag Filtering

# Run scenarios by tag
npx cucumber-js --tags "@critical"
npx cucumber-js --tags "@smoke or @critical"
npx cucumber-js --tags "not @wip and not @manual"

# Run specific feature file
npx cucumber-js features/auth/login.feature

API Contract Testing (from Tech Spec)

Assert exact response shapes, including status codes and error paths. Full patterns: references/integration-testing.md.

describe('POST /api/auth/login', () => {
  test('accepts valid credentials', async () => {
    const response = await request(app)
      .post('/api/auth/login')
      .send({ email: 'user@example.com', password: 'SecurePass123!' })
      .expect(200);

    expect(response.body).toEqual({
      token: expect.stringMatching(/^eyJ/),
      user: { id: expect.stringMatching(/^usr_/), email: 'user@example.com' },
      expiresIn: 3600
    });
  });

  test('returns 401 for invalid password', async () => {
    await request(app)
      .post('/api/auth/login')
      .send({ email: 'user@example.com', password: 'wrong' })
      .expect(401);
  });
});

Database Integration Testing

Use a real DB, reset state per test, assert constraints. More: references/integration-testing.md, references/test-data-factories.md.

describe('UserRepository', () => {
  beforeEach(async () => { await prisma.user.deleteMany(); });

  test('creates user with required fields', async () => {
    const user = await userRepository.create({ email: 'new@example.com', name: 'New User' });
    const dbUser = await prisma.user.findUnique({ where: { id: user.id } });
    expect(dbUser?.email).toBe('new@example.com');
  });

  test('enforces unique email', async () => {
    await userRepository.create({ email: 'existing@example.com' });
    await expect(userRepository.create({ email: 'existing@example.com' }))
      .rejects.toThrow('Email already exists');
  });
});

Unit Testing (Business Logic)

Cover the rule plus its boundary. More: references/test-patterns.md, references/test-writing-guide.md.

describe('calculateTotal', () => {
  test('applies percentage discount', () => {
    const items = [{ price: 100, quantity: 2 }, { price: 50, quantity: 1 }];
    expect(calculateTotal(items, { discountPercent: 10 })).toBe(225);
  });

  test('handles empty cart', () => {
    expect(calculateTotal([], {})).toBe(0);
  });
});

GUI Testing (DevTools MCP)

Drive the real UI through mcp.devtools and assert on resulting URL/text. Full operation set (navigation, forms, visual, accessibility, performance): references/gui-testing-mcp.md.

describe('Login Page', () => {
  test('successful login redirects to dashboard', async () => {
    await mcp.devtools.navigate('http://localhost:3000/login');
    await mcp.devtools.type('#email', 'user@example.com');
    await mcp.devtools.type('#password', 'SecurePass123!');
    await mcp.devtools.click('#submit-btn');
    await mcp.devtools.waitForNavigation();
    expect(await mcp.devtools.getCurrentUrl()).toBe('http://localhost:3000/dashboard');
  });

  test('shows error for invalid credentials', async () => {
    await mcp.devtools.navigate('http://localhost:3000/login');
    await mcp.devtools.type('#password', 'wrong');
    await mcp.devtools.click('#submit-btn');
    await mcp.devtools.waitForSelector('.error-message');
    expect(await mcp.devtools.getText('.error-message')).toBe('Invalid email or password');
  });
});

Test File Organization

tests/
  unit/services/, utils/, models/
  integration/api/, repositories/
  e2e/flows/, visual/, accessibility/
  factories/
  setup/database.ts, mcp.ts

Document-to-Test Mapping (Gherkin-First)

PRD → Tests:

PRD ArtifactTest TypeFile LocationCreated In
User StoriesCucumber feature filesfeatures/*.featurePhase 1 (PRD)
Acceptance CriteriaCucumber scenariosInside .feature filesPhase 1 (PRD)
Error Scenarios@error-handling scenariosInside .feature filesPhase 1 (PRD)
Edge Cases@edge-case scenariosInside .feature filesPhase 1 (PRD)

Tech Spec → Tests:

Tech Spec ArtifactTest TypeFile LocationCreated In
API ContractsIntegration teststests/integration/api/Phase 4 (Dev)
Database SchemaDB integration teststests/integration/db/Phase 4 (Dev)
Error ResponsesError scenario teststests/integration/errors/Phase 4 (Dev)
Business LogicUnit teststests/unit/Phase 4 (Dev)

Commands

Cucumber commands: see the BDD Test Execution table above.

# Unit/Integration Tests
npm test                           # All tests
npm test -- --testPathPattern=unit # Unit only
npm test -- --testPathPattern=integration
npm run test:e2e                   # GUI tests
npm test -- --coverage

Checklist Before Writing Tests

Cucumber (from PRD):

  • Feature files exist in features/ directory
  • npm run cucumber:dry shows undefined steps to implement
  • Research backing comments in feature files
  • Appropriate @tags on all scenarios

Other Tests:

  • Found latest PRD, Tech Spec, Plan
  • Confirmed with user
  • Extracted API contracts (Backend tests)
  • Extracted error scenarios
  • Identified test phases

Anti-Patterns

Detail and fixes: references/anti-patterns.md. Review gate: references/review-checklist.md.

Anti-PatternProblemFix
Testing implementationBrittleTest behavior/outcomes
Unrealistic mock dataMiss edge casesUse realistic factories
Only happy pathMiss errorsTest edge cases & errors
Order-dependent testsFlakyMake independent
Over-mockingMiss bugsReal integrations (<20% mocking)
Weak assertionsFalse positivesAssert exact values

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

AID Phase 4 - Development phase. Use for implementing features, TDD practices, code reviews, transitioning from planning to QA.

中文简介正在准备中。当前显示原文说明。

ilandahan/AID102026年9月23日 更新

AID Phase 0 - Research & discovery. Use for validating problem spaces, identifying stakeholders, defining success metrics, deciding whether to proceed.

中文简介正在准备中。当前显示原文说明。

ilandahan/AID102026年9月23日 更新

AID Phase 3 - Implementation Planning with consolidation-first approach. Resolves contradictions between PRD and Tech Spec, creates consolidated master document, then breaks down into actionable tasks and populates Jira. Includes sprint planning and risk assessment.

中文简介正在准备中。当前显示原文说明。

ilandahan/AID102026年9月23日 更新

aid-prd

免费

AID Phase 1 - PRD creation. Use for user stories, acceptance criteria, scoping features, transitioning from discovery to tech spec.

中文简介正在准备中。当前显示原文说明。

ilandahan/AID102026年9月23日 更新

AID Phase 5 - QA and Release. Use for validating implementations, acceptance tests, preparing releases, deployment, operational readiness.

中文简介正在准备中。当前显示原文说明。

ilandahan/AID102026年9月23日 更新

AID Phase 2 - Technical Specification. Use for system architecture, API contracts, data models, security architecture, transitioning from PRD to implementation.

中文简介正在准备中。当前显示原文说明。

ilandahan/AID102026年9月23日 更新

查看 ilandahan 的全部技能

报告此技能的问题