在创建新功能、修复 Bug 或重构代码时使用此技能。强制执行测试驱动开发(TDD),要求包括单元测试、集成测试和 E2E 测试在内的测试覆盖率达到 80% 以上。
65
77%
Does it follow best practices?
Run evals on this skill
Adds up to 20 points to the overall score
View guide
Passed
No findings from the security scan
Fix and improve this skill with Tessl
tessl review fix ./docs/ja-JP/skills/tdd-workflow/SKILL.md此技能(Skill)旨在确保所有代码开发都遵循具有全面测试覆盖率的测试驱动开发(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 () => {
// Mock 数据库故障
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')
// 等待防抖(Debounce)和结果返回
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/
│ ├── 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.tsjest.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) // Mock 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请记住:测试不是可选的。它是让你能够自信地重构、快速地开发并确保生产环境可靠性的安全网。
dfbf946
If you maintain this skill, you can claim it as your own. Once claimed, you can manage eval scenarios, bundle related skills, attach documentation or rules, and ensure cross-agent compatibility.