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 whether it tested the right thing.
Violating the letter of the rules is violating the spirit of the rules.
When to use
Always use for:
- New features
- Bug fixes
- Refactoring
- Behavior changes
Exceptions (ask your human partner):
- One-off prototypes
- Generated code
- Configuration files
Thinking "skip TDD this time"? Stop. That's a rationalization.
Iron law
NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST
Wrote code first and then wrote 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
- Delete means delete
Reimplement from the tests. That's it.
Red-Green-Refactor
digraph tdd_cycle {
rankdir=LR;
red [label="RED\nWrite failing test", shape=box, style=filled, fillcolor="#ffcccc"];
verify_red [label="Verify fails\ncorrectly", shape=diamond];
green [label="GREEN\nMinimal code", shape=box, style=filled, fillcolor="#ccffcc"];
verify_green [label="Verify passes\nAll green", shape=diamond];
refactor [label="REFACTOR\nClean up", shape=box, style=filled, fillcolor="#ccccff"];
next [label="Next", shape=ellipse];
red -> verify_red;
verify_red -> green [label="yes"];
verify_red -> red [label="wrong\nfailure"];
green -> verify_green;
verify_green -> refactor [label="yes"];
verify_green -> green [label="no"];
refactor -> verify_green [label="stay\ngreen"];
verify_green -> next;
next -> red;
}
RED - Write a failing test
Write a minimal test that shows what should happen.
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 instead of code
Requirements:
- One behavior
- Clear name
- Real code (unless unavoidable, don't use mocks)
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
- It fails because the feature is missing (not a typo)
Test passed? You tested existing behavior. Fix the test.
Test errored? Fix the error, rerun, until it fails correctly.
GREEN - Minimal code
Write the simplest code that makes 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)
Test failed? Fix the code, not the test.
Other tests failed? Fix them now.
REFACTOR - Clean up
Only after green:
- Remove duplication
- Improve naming
- Extract helpers
Keep tests green. Don't add behavior.
Repeat
Write the next failing test for the next feature.
Good tests
| Quality | Good | Bad |
|---|---|---|
| Minimal | One thing. Has "and" in the name? Split it. | test('validates email and domain and whitespace') |
| Clear | The name describes the behavior | test('test1') |
| Shows intent | Shows the expected API | Obscures what the code should do |
Why order matters
"I'll write tests later to verify it works"
Tests written after the code will pass immediately. Passing immediately proves nothing:
- Might have tested the wrong thing
- Might be testing the implementation, not the behavior
- Might 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 actually tests something.
"I've already manually tested all the edge cases"
Manual testing is ad hoc. You think you tested everything, but:
- There's no record of what you tested
- Can't be re-run when the code changes
- Easy to forget cases under pressure
- "It worked when I tried it" ≠ comprehensive
Automated tests are systematic. They run the same way every time.
"Deleting X hours of work is a waste"
Sunk cost fallacy. The time is already spent. Your choices now are:
- Delete and rewrite with TDD (another X hours, high confidence)
- Keep it and add tests afterward (30 minutes, low confidence, possibly buggy)
The real "waste" is keeping code you can't trust. Working code without real tests is technical debt.
"TDD is dogmatic; being pragmatic means adjusting flexibly"
TDD is pragmatic:
- Catches bugs before committing (faster than debugging afterward)
- Prevents regressions (tests immediately catch breakage)
- Documents behavior (tests show how to use the code)
- Supports refactoring (change freely, tests catch breakage)
The "pragmatic" shortcut = debugging in production = slower.
"Testing afterward achieves the same goal—the spirit matters, not the ritual"
No. Testing afterward answers "What did this do?" Testing first answers "What should this do?"
Testing afterward is influenced by your implementation bias. You test what you built, not what the requirements demand. You verify the edge cases you remember, not the edge cases you discover.
Testing first forces you to discover edge cases before implementing. Testing afterward is verifying that you remembered everything (you didn't).
Adding tests afterward in 30 minutes ≠ TDD. You get coverage, but you lose proof that the tests are effective.
Common rationalizations
| Excuse | Reality |
|---|---|
| "It's too simple to test" | Simple code breaks too. Testing takes only 30 seconds. |
| "I'll test it later" | Tests passing immediately prove nothing. |
| "Testing afterward achieves the same goal" | Testing afterward = "What did this do?" Testing first = "What should this do?" |
| "I've already manually tested it" | Ad hoc ≠ systematic. No record, can't be re-run. |
| "Deleting X hours of work is a waste" | Sunk cost fallacy. Keeping unverified code is technical debt. |
| "Keep it for reference, write tests first" | You'll adapt it. That's testing afterward. Deleting is deleting. |
| "Need to explore first" | Okay. Discard the exploration code, then start with TDD. |
| "Tests are hard = design is unclear" | Listen to the tests. Hard to test = hard to use. |
| "TDD will slow me down" | TDD is faster than debugging. Pragmatic = test first. |
| "Manual testing is faster" | Manual testing cannot prove edge cases. Retest on every change. |
| "Existing code has no tests" | You are improving it. Add tests for existing code. |
Red flags — stop and start over
- Write code first, tests later
- Test after implementation
- Test passes immediately
- Cannot explain why the test fails
- Add tests "later"
- Rationalize with "just this once"
- "I already tested it manually"
- "Testing afterward achieves the same goal"
- "The spirit matters, not the ritual"
- "Keep it for reference" or "adapt existing code"
- "Already spent X hours, deleting is too wasteful"
- "TDD is dogmatic, I'm being pragmatic"
- "This time is different because..."
All of these mean: delete the code. Start over with TDD.
Example: Bug fix
Bug: Empty email is 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 for multiple fields.
Verification checklist
Before marking work complete:
- Every new function/method has a test
- Watched each test fail before implementation
- 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 (use mocks only when unavoidable)
- Covers edge cases and errors
Can't check all the boxes? You skipped TDD. Start over.
When stuck
| Problem | Solution |
|---|---|
| Don't know how to test | Write out the desired API. Write the assertion first. Ask your human partner. |
| Test is too complex | Design is too complex. Simplify the interface. |
| Must mock everything | Code is too coupled. Use dependency injection. |
| Test setup is huge | Extract a helper. Still complex? Simplify the design. |
Debugging integration
Found a bug? Write a failing test to reproduce it. Follow the TDD cycle. The test 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
- Mocking without understanding dependencies
Final rule
Production code → test exists and failed first
Otherwise → not TDD
No exceptions are allowed without the permission of your human partner.