Overview
Write the test first. Watch it fail. Write the minimal code to make it pass.
Core principles: If you didn't see the test fail, you don't know whether it tested the right thing.
Violating the letter of the rule is violating the spirit of the rule.
When to use
Always use:
- New features
- Bug fixes
- Refactoring
- Behavior changes
Exceptions (ask your human partner):
- One-off prototypes
- Generated code
- Configuration files
Thinking "just this once, skip TDD"? Stop. That's making excuses for yourself.
Iron law
没有失败的测试,就不写生产代码
Wrote the code first and then the test? Delete it. Start over.
No exceptions:
- Don't keep it as a "reference"
- Don't "adapt" it while writing the test
- Don't look at it
- Deleting means deleting
Start from the test 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 desired 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 unavoidable)
Verify red - Watch it fail
Mandatory. Never skip.
npm test path/to/test.test.ts
Confirm:
- The test fails (not errors)
- The failure message matches expectations
- The failure is due to missing functionality (not a typo)
The test passed? You're testing existing behavior. Modify the test.
The test errored? 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:
- The test passes
- Other tests still pass
- Output is clean (no errors, warnings)
The test failed? Modify the code, not the test.
Other tests failed? Fix immediately.
Refactor - Clean up the code
Only refactor after green:
- Eliminate duplication
- Improve naming
- Extract helper functions
Keep tests green. Don't add behavior.
Repeat
Write the next failing test for the next feature.
Good tests
| Traits | Good | Bad |
|---|---|---|
| Minimal | Test only one thing. "And" in the name? Split it. | test('validates email and domain and whitespace') |
| Clear | Name describes the behavior | test('test1') |
| Express intent | Demonstrate the desired API | Obscured 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:
- It may test the wrong thing
- It may test the implementation rather than the behavior
- It may miss edge cases you forgot
- You never see it catch a bug
Writing the test 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 tests
- They cannot be rerun after the code changes
- They are easy to forget under pressure
- "I tried it and it runs" does not equal 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)
What is "wasted" 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.
"Tests added afterward can achieve the same purpose—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 demand. 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 tests added afterward ≠ TDD. You get coverage, but you lose proof that the tests are effective.
Common excuses
| Excuse | Reality |
|---|---|
| "It's too simple to test" | Simple code also has bugs. Testing takes only 30 seconds. |
| "I'll add tests later" | Tests that pass immediately prove nothing. |
| "Tests added afterward can achieve the same purpose" | 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, not reproducible. |
| "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 a bit first" | Okay. Throw it away after exploring, and start with TDD. |
| "Tests are hard to write = the design is unclear" | Listen to the tests. Hard to test = hard to use. |
| "TDD will slow me down" | TDD is faster than debugging. Pragmatic = write tests first. |
| "Manual testing is faster" | Manual testing cannot prove edge cases. You have to retest after every change. |
| "The existing code has no tests" | You are improving it. Add tests for the existing code. |
Red flags - stop, start over
- Wrote the code first and then the tests
- Added tests only after the implementation was done
- The test passes immediately
- Cannot explain why the test fails
- "Add it later" tests
- Convincing yourself "just this once"
- "I already tested it manually"
- "Adding tests later achieves the same goal"
- "What matters is the spirit, not the ritual"
- "Keep it for reference" or "adapt existing code"
- "I already spent X hours, deleting it would be a waste"
- "TDD is too dogmatic, I am 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 the validation logic to support multiple fields.
Verification checklist
Before marking work as complete:
- Every new function/method has a test
- Saw each test fail before implementing
- Each test failed for the expected reason (missing functionality, not a typo)
- Wrote the minimum code to make each test pass
- All tests pass
- Output is clean (no errors, warnings)
- Tests use real code (only use mocks when unavoidable)
- Covered edge cases and error scenarios
Cannot check all the boxes? You skipped TDD. Start over.
When you get stuck
| Problem | Solution |
|---|---|
| Don't know how to test it | Write out the API you expect. Write the assertion first. Ask your human partner. |
| The test is too complex | The design is too complex. Simplify the interface. |
| Have to mock everything | The code is too tightly coupled. Use dependency injection. |
| The 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. Follow 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
- Adding test-only methods to production classes
- Using mocks without understanding the dependencies
Final rule
生产代码 → 测试存在且先失败
否则 → 不是 TDD
No exceptions without the permission of your human partner.