Overview
Write the test first. Watch it fail. Write the minimal code to make it pass.
Core principle: If you didn't watch the test fail, you don't know if it tests the right thing.
Violating the letter of the rules is violating the spirit of the rules.
When to Use
Always use:
- New features
- Bug fixes
- Refactoring
- Behavior changes
Exceptions (ask your human partner):
- Throwaway prototypes
- Generated code
- Configuration files
Thinking "just this once, skip TDD"? Stop. That's making excuses for yourself.
The Iron Law
没有失败的测试,就不写生产代码
Wrote code before writing tests? Delete it. Start over.
No exceptions:
- Don't keep it as a "reference"
- Don't "adapt" it while writing tests
- Don't look at it
- Deleting means deleting
Start from the tests and reimplement. Period.
Red-Green-Refactor
digraph tdd_cycle {
rankdir=LR;
red [label="红灯\n编写失败的测试", shape=box, style=filled, fillcolor="#ffcccc"];
verify_red [label="验证正确失败", shape=diamond];
green [label="绿灯\n最少代码", shape=box, style=filled, fillcolor="#ccffcc"];
verify_green [label="验证通过\n全部绿灯", shape=diamond];
refactor [label="重构\n清理代码", shape=box, style=filled, fillcolor="#ccccff"];
next [label="下一个", shape=ellipse];
red -> verify_red;
verify_red -> green [label="是"];
verify_red -> red [label="错误的\n失败"];
green -> verify_green;
verify_green -> refactor [label="是"];
verify_green -> green [label="否"];
refactor -> verify_green [label="保持\n绿灯"];
verify_green -> next;
next -> red;
}
Red - Write a failing test
Write a minimal test to demonstrate the expected behavior.
const result = await retryOperation(operation);
expect(result).toBe('success'); expect(attempts).toBe(3); });
名称清晰,测试真实行为,只测一件事
</Good>
<Bad>
```typescript
test('retry works', async () => {
const mock = jest.fn()
.mockRejectedValueOnce(new Error())
.mockRejectedValueOnce(new Error())
.mockResolvedValueOnce('success');
await retryOperation(mock);
expect(mock).toHaveBeenCalledTimes(3);
});
Vague name, tests mocks rather than code
Requirements:
- One behavior
- Clear name
- Use real code (only use mocks when you have no other choice)
Verify red - Watch it fail
Mandatory. Never skip.
npm test path/to/test.test.ts
Confirm:
- Test fails (not errors)
- Failure message matches expectations
- Failure is due to missing functionality (not a typo)
Test passes? You're testing existing behavior. Modify the test.
Test errors? Fix the error, rerun until it fails correctly.
Green - Minimal code
Write the simplest code to make the test pass.
Don't add features, refactor other code, or make "improvements" beyond what the test requires.
Verify green - Watch it pass
Mandatory.
npm test path/to/test.test.ts
Confirm:
- Test passes
- Other tests still pass
- Output is clean (no errors, no warnings)
Test failed? Fix the code, not the test.
Other tests failed? Fix them immediately.
Refactor - Clean up the code
Refactor only after green:
- Eliminate duplication
- Improve naming
- Extract helper functions
Keep the tests green. Don't add behavior.
Repeat
Write the next failing test for the next feature.
Good Tests
| Quality | Good | Bad |
|---|---|---|
| Minimal | Tests only one thing. Have "and" in the name? Split it. | test('validates email and domain and whitespace') |
| Clear | Name describes the behavior | test('test1') |
| Shows intent | Shows the expected API | Masked what the code is supposed to do |
Why order matters
"I'll write it first and then add tests to verify"
Tests written afterward pass immediately. Passing immediately proves nothing:
- May have tested the wrong thing
- May have tested the implementation rather than the behavior
- May have missed edge cases you forgot
- You never saw it catch a bug
Writing tests first forces you to see the test fail, proving it is actually testing something.
"I've already manually tested all the edge cases"
Manual testing is ad hoc. You think you tested all the cases, but:
- There is no record of the testing
- It cannot be rerun after code changes
- It is easy to forget under pressure
- "I tried it and it ran" is not the same as comprehensive testing
Automated tests are systematic. They run the same way every time.
"Deleting X hours of work is too wasteful"
Sunk cost fallacy. The time is already spent. Your choices now:
- Delete and rewrite with TDD (another X hours, high confidence)
- Keep it and add tests afterward (30 minutes, low confidence, possibly buggy)
The "waste" is keeping code you cannot trust. Runnable code without real tests is technical debt.
"TDD is too dogmatic; being pragmatic means being flexible"
TDD is pragmatic:
- Finds bugs before commit (faster than debugging after the fact)
- Prevents regressions (tests catch breakage immediately)
- Documents behavior (tests show how to use the code)
- Supports refactoring (modify with confidence, tests catch breakage)
The "pragmatic" shortcut = debugging in production = slower.
"Adding tests afterward can achieve the same goal too—what matters is the spirit, not the ritual"
No. Tests added afterward answer "What does this code do?" Writing tests first answers "What should this code do?"
Tests added afterward are biased by your implementation. You test what you built, not what the requirements demanded. You verify the edge cases you remember, not the ones you discover.
Writing tests first forces you to discover edge cases before implementation. Tests added afterward verify that you remembered all the cases (you didn't).
30 minutes of adding tests afterward ≠ TDD. You get coverage, but you lose proof that the tests are effective.
Common excuses
| Excuse | Reality |
|---|---|
| "It's too simple to need tests" | Simple code can have bugs too. A test takes only 30 seconds. |
| "I'll add tests later" | Tests that pass immediately prove nothing. |
| "Adding tests afterward can achieve the same goal too" | Tests added afterward = "What does this do?" Writing tests first = "What should this do?" |
| "I've already tested it manually" | Ad hoc testing ≠ systematic testing. No record, no reproducibility. |
| "Deleting X hours of work is too wasteful" | Sunk cost fallacy. Keeping unverified code is technical debt. |
| "Keep it for reference, then write tests first" | You will adapt it. That is adding tests afterward. Deleting means deleting. |
| "Need to explore first" | Fine. Throw it away when done exploring, start with TDD. |
| "Tests are hard to write = design is unclear" | Listen to the tests. Hard to test = hard to use. |
| "TDD slows me down" | TDD is faster than debugging. Pragmatic = write tests first. |
| "Manual testing is faster" | Manual testing can't prove edge cases. You have to re-test after every change. |
| "Existing code has no tests" | You're improving it. Add tests for existing code. |
Red flags - stop, start over
- Wrote code before writing tests
- Added tests only after implementation was done
- Test passes immediately
- Can't explain why the test failed
- "Add tests later"
- Convincing yourself "just this once"
- "I already tested it manually"
- "Adding tests afterwards achieves the same thing"
- "What matters is the spirit, not the ritual"
- "Keep for reference" or "adapt existing code"
- "Already spent X hours, deleting is too wasteful"
- "TDD is too dogmatic, I'm being pragmatic"
- "This time is different, because..."
All of the above mean: delete the code. Start over with TDD.
Example: Bug fix
Bug: Empty email was accepted
Red
test('rejects empty email', async () => {
const result = await submitForm({ email: '' });
expect(result.error).toBe('Email required');
});
Verify red
$ npm test
FAIL: expected 'Email required', got undefined
Green
function submitForm(data: FormData) {
if (!data.email?.trim()) {
return { error: 'Email required' };
}
// ...
}
Verify green
$ npm test
PASS
Refactor If needed, extract validation logic to support multiple fields.
Verification checklist
Before marking work as complete:
- Every new function/method has tests
- Saw every test fail before implementation
- Every test failed for the expected reason (missing functionality, not a typo)
- Wrote the minimum code for each test to make it pass
- All tests pass
- Output is clean (no errors, warnings)
- Tests use real code (only use mocks when unavoidable)
- Edge cases and error scenarios are covered
Can't check them all? You skipped TDD. Start over.
When you get stuck
| Problem | Solution |
|---|---|
| Don't know how to test | Write out the API you expect. Write the assertions first. Ask your human partner. |
| Tests are too complex | The design is too complex. Simplify the interface. |
| Have to mock everything | The code is too tightly coupled. Use dependency injection. |
| Test setup is too large | Extract helper functions. Still complex? Simplify the design. |
Debugging integration
Found a bug? Write a failing test that reproduces the bug. Go through the TDD cycle. The test both proves the fix works and prevents regressions.
Never fix a bug without a test.
Testing anti-patterns
When adding mocks or test utilities, read @testing-anti-patterns.md to avoid common pitfalls:
- Testing mock behavior instead of real behavior
- Add test-only methods to production classes
- Use mocks without understanding dependencies
Final Rule
生产代码 → 测试存在且先失败
否则 → 不是 TDD
No exceptions without permission from your human partner.