Loading...
Loading...
Compare original and translation side by side
--tdd--tddNO PRODUCTION CODE WITHOUT A FAILING TEST FIRSTNO PRODUCTION CODE WITHOUT A FAILING TEST FIRSTRED → Verify RED → GREEN → Verify GREEN → REFACTOR → RepeatRED → 验证RED状态 → GREEN → 验证GREEN状态 → REFACTOR → 重复test('retries failed operations 3 times', async () => {
let attempts = 0;
const operation = () => {
attempts++;
if (attempts < 3) throw new Error('fail');
return 'success';
};
const result = await retryOperation(operation);
expect(result).toBe('success');
expect(attempts).toBe(3);
});test('retry works', async () => {
const mock = jest.fn()
.mockRejectedValueOnce(new Error())
.mockRejectedValueOnce(new Error())
.mockResolvedValueOnce('success');
await retryOperation(mock);
expect(mock).toHaveBeenCalledTimes(3);
});test('retries failed operations 3 times', async () => {
let attempts = 0;
const operation = () => {
attempts++;
if (attempts < 3) throw new Error('fail');
return 'success';
};
const result = await retryOperation(operation);
expect(result).toBe('success');
expect(attempts).toBe(3);
});test('retry works', async () => {
const mock = jest.fn()
.mockRejectedValueOnce(new Error())
.mockRejectedValueOnce(new Error())
.mockResolvedValueOnce('success');
await retryOperation(mock);
expect(mock).toHaveBeenCalledTimes(3);
});npm test path/to/test.test.tsnpm test path/to/test.test.tsasync function retryOperation<T>(fn: () => Promise<T>): Promise<T> {
for (let i = 0; i < 3; i++) {
try {
return await fn();
} catch (e) {
if (i === 2) throw e;
}
}
throw new Error('unreachable');
}async function retryOperation<T>(
fn: () => Promise<T>,
options?: {
maxRetries?: number;
backoff?: 'linear' | 'exponential';
onRetry?: (attempt: number) => void;
}
): Promise<T> {
// YAGNI - You Aren't Gonna Need It
}async function retryOperation<T>(fn: () => Promise<T>): Promise<T> {
for (let i = 0; i < 3; i++) {
try {
return await fn();
} catch (e) {
if (i === 2) throw e;
}
}
throw new Error('unreachable');
}async function retryOperation<T>(
fn: () => Promise<T>,
options?: {
maxRetries?: number;
backoff?: 'linear' | 'exponential';
onRetry?: (attempt: number) => void;
}
): Promise<T> {
// YAGNI - 你不会用到这些
}npm test path/to/test.test.tsnpm test path/to/test.test.tsundefinedundefined
Activates enhanced TDD mode with:
- Automatic checkpoint prompts
- Cycle tracking
- Test coverage monitoring
- Enforced verification steps
激活增强型TDD模式,包含:
- 自动检查点提示
- 循环跟踪
- 测试覆盖率监控
- 强制验证步骤undefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedpython scripts/session.py end --handoffpython scripts/session.py end --handoff| Quality | Good | Bad |
|---|---|---|
| Minimal | One thing. "and" in name? Split it. | |
| Clear | Name describes behavior | |
| Shows intent | Demonstrates desired API | Obscures what code should do |
| 质量维度 | 好的测试 | 差的测试 |
|---|---|---|
| 最小化 | 只测试一件事。名称中有“和”?拆分它。 | |
| 清晰性 | 名称描述行为 | |
| 意图明确 | 展示期望的API | 模糊代码应有的行为 |
| Excuse | Reality |
|---|---|
| "Too simple to test" | Simple code breaks. Test takes 30 seconds. |
| "I'll test after" | Tests passing immediately prove nothing. |
| "Tests after achieve same goals" | Tests-after = "what does this do?" Tests-first = "what should this do?" |
| "Already manually tested" | Ad-hoc ≠ systematic. No record, can't re-run. |
| "Deleting X hours is wasteful" | Sunk cost fallacy. Keeping unverified code is technical debt. |
| "Keep as reference, write tests first" | You'll adapt it. That's testing after. Delete means delete. |
| "Need to explore first" | Fine. Throw away exploration, start with TDD. |
| "Test hard = design unclear" | Listen to test. Hard to test = hard to use. |
| "TDD will slow me down" | TDD faster than debugging. Pragmatic = test-first. |
| "Manual test faster" | Manual doesn't prove edge cases. You'll re-test every change. |
| "Existing code has no tests" | You're improving it. Add tests for existing code. |
| 借口 | 现实 |
|---|---|
| “太简单了,不需要测试” | 简单代码也会出错,写测试只需要30秒。 |
| “我之后再写测试” | 立即通过的测试无法证明任何事情。 |
| “后写测试也能达到同样目标” | 后写测试=“这段代码做了什么?”,先写测试=“这段代码应该做什么?” |
| “已经手动测试过了” | 临时测试≠系统化测试,没有记录,无法重跑。 |
| “删掉X小时的工作太浪费了” | 沉没成本谬误,保留未验证的代码是技术债务。 |
| “保留作为参考,先写测试” | 你会忍不住改编它,这本质上还是后写测试。删就是彻底删掉。 |
| “需要先探索一下” | 没问题,扔掉探索性代码,用TDD重新开始。 |
| “测试难写=设计不清晰” | 倾听测试的反馈:难测试的代码也难使用。 |
| “TDD会拖慢我的速度” | TDD比调试更快,务实的做法就是先写测试。 |
| “手动测试更快” | 手动测试无法覆盖所有边缘情况,每次代码变更你都要重新测试。 |
| “现有代码没有测试” | 你正在改进它,为现有代码添加测试。 |
test('rejects empty email', async () => {
const result = await submitForm({ email: '' });
expect(result.error).toBe('Email required');
});$ npm test
FAIL: expected 'Email required', got undefinedfunction submitForm(data: FormData) {
if (!data.email?.trim()) {
return { error: 'Email required' };
}
// ...
}$ npm test
PASStest('rejects empty email', async () => {
const result = await submitForm({ email: '' });
expect(result.error).toBe('Email required');
});$ npm test
FAIL: expected 'Email required', got undefinedfunction submitForm(data: FormData) {
if (!data.email?.trim()) {
return { error: 'Email required' };
}
// ...
}$ npm test
PASS| Problem | Solution |
|---|---|
| Don't know how to test | Write wished-for API. Write assertion first. Ask your human partner. |
| Test too complicated | Design too complicated. Simplify interface. |
| Must mock everything | Code too coupled. Use dependency injection. |
| Test setup huge | Extract helpers. Still complex? Simplify design. |
| 问题 | 解决方案 |
|---|---|
| 不知道如何测试 | 写出你期望的API,先写断言,咨询团队成员。 |
| 测试太复杂 | 设计太复杂,简化接口。 |
| 必须到处用模拟对象 | 代码耦合度太高,使用依赖注入。 |
| 测试设置太繁琐 | 提取辅助函数。如果还是复杂?简化设计。 |
Production code → test exists and failed first
Otherwise → not TDDProduction code → test exists and failed first
Otherwise → not TDD.ccmp/state.json.ccmp/state.jsonfrom lib.ccmp_integration import is_session_active, is_tdd_mode
if is_session_active():
# Enhanced TDD mode with session integration
pass.git/sessions/<branch>/--tddsession.pyfrom lib.ccmp_integration import is_session_active, is_tdd_mode
if is_session_active():
# 带会话集成的增强型TDD模式
pass.git/sessions/<branch>/--tddsession.pypython scripts/session.py start feature/auth --tddpython scripts/session.py start feature/auth --tdd
**TDD metrics in sessions:**
- Cycles completed tracked in session state
- Session status shows TDD discipline score
- Handoffs include test coverage metrics
**会话中的TDD指标:**
- 会话状态中跟踪已完成的循环数
- 会话状态显示TDD准则遵守得分
- 交接文档包含测试覆盖率指标tests/*/claude.mdfrom lib.ccmp_integration import CCMPIntegration
integration = CCMPIntegration()
integration.update_state("tdd-workflow", {
"active": True,
"cycles_today": 5,
"current_phase": "GREEN",
"discipline_score": 100
})tests/*/claude.mdfrom lib.ccmp_integration import CCMPIntegration
integration = CCMPIntegration()
integration.update_state("tdd-workflow", {
"active": True,
"cycles_today": 5,
"current_phase": "GREEN",
"discipline_score": 100
})