一键导入
tdd-workflow
在编写新功能、修复 Bug 或重构代码时使用此技能。强制执行测试驱动开发 (TDD),包括单元测试、集成测试和端到端 (E2E) 测试,确保覆盖率达到 80% 以上。
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
在编写新功能、修复 Bug 或重构代码时使用此技能。强制执行测试驱动开发 (TDD),包括单元测试、集成测试和端到端 (E2E) 测试,确保覆盖率达到 80% 以上。
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
Response wrapping, pagination, and error standardization.
Universal coding standards, best practices, and patterns for TypeScript, JavaScript, React, and Node.js development.
This skill leverages the database-diff-tool plugin to compare database schemas, generate migration scripts, and provide rollback procedures. It is triggered when the user requests database schema comparisons, migration script generation, or database synchronization. Use this skill when asked to identify differences between database schemas (PostgreSQL or MySQL), create safe migration scripts with transaction safety, validate changes before deployment, or generate rollback procedures. The skill is activated by requests involving terms like "database diff", "schema comparison", "generate migration script", "database synchronization", or `/db-diff`.
Create a database migration to add a table, add columns to an existing table, add a setting, or otherwise change the schema of Ghost's MySQL database.
Database performance optimization, schema design, query analysis, and connection management across PostgreSQL, MySQL, MongoDB, and SQLite with ORM integration. Use this skill for queries, indexes, connection pooling, transactions, and database architecture decisions.
Master error handling patterns across languages including exceptions, Result types, error propagation, and graceful degradation to build resilient applications. Use when implementing error handling, designing APIs, or improving application reliability.
| name | tdd-workflow (测试驱动开发工作流) |
| description | 在编写新功能、修复 Bug 或重构代码时使用此技能。强制执行测试驱动开发 (TDD),包括单元测试、集成测试和端到端 (E2E) 测试,确保覆盖率达到 80% 以上。 |
本技能确保所有代码开发遵循 TDD 原则,并具有全面的测试覆盖率。
始终先编写测试,然后实现代码以使测试通过。
作为 [角色],我想要 [行动],以便 [收益]
示例:
作为用户,我想要进行语义化的市场搜索,
以便即使没有确切的关键词也能找到相关的市场。
为每个用户旅程创建全面的测试用例:
describe('Semantic Search', () => {
it('returns relevant markets for query', async () => {
// 测试实现
})
it('handles empty query gracefully', async () => {
// 测试边缘情况
})
it('falls back to substring search when Redis unavailable', async () => {
// 测试回退行为
})
it('sorts results by similarity score', async () => {
// 测试排序逻辑
})
})
npm test
# 测试应失败 - 我们尚未实现
编写最少量的代码以使测试通过:
// 由测试引导的实现
export async function searchMarkets(query: string) {
// 在此实现
}
npm test
# 测试现在应通过
在保持测试通过的前提下提高代码质量:
npm run test:coverage
# 验证是否达到 80%+ 覆盖率
import { render, screen, fireEvent } from '@testing-library/react'
import { Button } from './Button'
describe('Button Component', () => {
it('renders with correct text', () => {
render(<Button>Click me</Button>)
expect(screen.getByText('Click me')).toBeInTheDocument()
})
it('calls onClick when clicked', () => {
const handleClick = jest.fn()
render(<Button onClick={handleClick}>Click</Button>)
fireEvent.click(screen.getByRole('button'))
expect(handleClick).toHaveBeenCalledTimes(1)
})
it('is disabled when disabled prop is true', () => {
render(<Button disabled>Click</Button>)
expect(screen.getByRole('button')).toBeDisabled()
})
})
import { NextRequest } from 'next/server'
import { GET } from './route'
describe('GET /api/markets', () => {
it('returns markets successfully', async () => {
const request = new NextRequest('http://localhost/api/markets')
const response = await GET(request)
const data = await response.json()
expect(response.status).toBe(200)
expect(data.success).toBe(true)
expect(Array.isArray(data.data)).toBe(true)
})
it('validates query parameters', async () => {
const request = new NextRequest('http://localhost/api/markets?limit=invalid')
const response = await GET(request)
expect(response.status).toBe(400)
})
it('handles database errors gracefully', async () => {
// 模拟数据库故障
const request = new NextRequest('http://localhost/api/markets')
// 测试错误处理
})
})
import { test, expect } from '@playwright/test'
test('user can search and filter markets', async ({ page }) => {
// 导航到市场页面
await page.goto('/')
await page.click('a[href="/markets"]')
// 验证页面加载
await expect(page.locator('h1')).toContainText('Markets')
// 搜索市场
await page.fill('input[placeholder="Search markets"]', 'election')
// 等待防抖和结果
await page.waitForTimeout(600)
// 验证搜索结果显示
const results = page.locator('[data-testid="market-card"]')
await expect(results).toHaveCount(5, { timeout: 5000 })
// 验证结果包含搜索词
const firstResult = results.first()
await expect(firstResult).toContainText('election', { ignoreCase: true })
// 按状态过滤
await page.click('button:has-text("Active")')
// 验证过滤结果
await expect(results).toHaveCount(3)
})
test('user can create a new market', async ({ page }) => {
// 先登录
await page.goto('/creator-dashboard')
// 填写市场创建表单
await page.fill('input[name="name"]', 'Test Market')
await page.fill('textarea[name="description"]', 'Test description')
await page.fill('input[name="endDate"]', '2025-12-31')
// 提交表单
await page.click('button[type="submit"]')
// 验证成功消息
await expect(page.locator('text=Market created successfully')).toBeVisible()
// 验证重定向到市场页面
await expect(page).toHaveURL(/\/markets\/test-market/)
})
src/
├── components/
├── components/
│ ├── Button/
│ │ ├── Button.tsx
│ │ ├── Button.test.tsx # 单元测试
│ │ └── Button.stories.tsx # Storybook
│ └── MarketCard/
│ ├── MarketCard.tsx
│ └── MarketCard.test.tsx
├── app/
│ └── api/
│ └── markets/
│ ├── route.ts
│ └── route.test.ts # 集成测试
└── e2e/
├── markets.spec.ts # E2E 测试
├── trading.spec.ts
└── auth.spec.ts
jest.mock('@/lib/supabase', () => ({
supabase: {
from: jest.fn(() => ({
select: jest.fn(() => ({
eq: jest.fn(() => Promise.resolve({
data: [{ id: 1, name: 'Test Market' }],
error: null
}))
}))
}))
}
}))
jest.mock('@/lib/redis', () => ({
searchMarketsByVector: jest.fn(() => Promise.resolve([
{ slug: 'test-market', similarity_score: 0.95 }
])),
checkRedisHealth: jest.fn(() => Promise.resolve({ connected: true }))
}))
jest.mock('@/lib/openai', () => ({
generateEmbedding: jest.fn(() => Promise.resolve(
new Array(1536).fill(0.1) // 模拟 1536 维向量
))
}))
npm run test:coverage
{
"jest": {
"coverageThresholds": {
"global": {
"branches": 80,
"functions": 80,
"lines": 80,
"statements": 80
}
}
}
}
// 不要测试内部状态
expect(component.state.count).toBe(5)
// 测试用户看到的内容
expect(screen.getByText('Count: 5')).toBeInTheDocument()
// 容易因修改而中断
await page.click('.css-class-xyz')
// 对变更具有弹性
await page.click('button:has-text("Submit")')
await page.click('[data-testid="submit-button"]')
// 测试相互依赖
test('creates user', () => { /* ... */ })
test('updates same user', () => { /* 依赖于前一个测试 */ })
// 每个测试设置自己的数据
test('creates user', () => {
const user = createTestUser()
// 测试逻辑
})
test('updates user', () => {
const user = createTestUser()
// 更新逻辑
})
npm test -- --watch
# 文件更改时自动运行测试
# 每次提交前运行
npm test && npm run lint
# GitHub Actions
- name: Run Tests
run: npm test -- --coverage
- name: Upload Coverage
uses: codecov/codecov-action@v3
记住:测试不是可选项。它们是能够实现自信重构、快速开发和生产可靠性的安全网。