Overview
Write the test first. Watch it fail. Write the minimum code to make it pass.
Core principle: If you didn't watch the test fail, you don't know if it tested 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):
- One-off prototypes
- Generated code
- Configuration files
Thinking "just this once, skip TDD"? Stop. That's making excuses for yourself.
The Iron Law
没有失败的测试,就不写生产代码
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
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 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 a mock rather than the 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:
- 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 and rerun until it fails correctly.
Green - Minimum 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 them immediately.
"Other tests" means the project's entire test suite, not just your file. Your test running green doesn't mean the test suite is green. Before claiming the change is complete, run the project's test command (directly pytest、npm test、cargo test—whatever the repository uses, run that), even if your task names only one test file. The scope statement in the task constrains the deliverable, not your verification. Any failure that run exposes—including ones you didn't cause—must be called out by name in the report; a red test you watched scroll by and didn't mention is a report falsified by omission.
Refactor - Clean up the code
Only refactor after green:
- Eliminate duplication
- Improve naming
- Extract helper functions
Keep the tests green. Do not add behavior.
Duplicate
Write the next failing test for the next feature.
Good tests
| Trait | Good | Bad |
|---|---|---|
| Minimal | Tests one thing. "And" in the name? Split it. | test('validates email and domain and whitespace') |
| Clear | Name describes the behavior | test('test1') |
| Shows intent | Shows the desired API | Obscures what the code should do |
When writing any test, or modifying any test, read writing-good-tests.md, where the rules that keep tests honest are:
- Before writing it, name the production code change that would make the test fail
- Assert real behavior, never assert mock behavior
- Code only used by tests goes in test helpers, not production classes
- Before mocking a dependency, first understand its side effects
Common excuses
| Excuse | Reality |
|---|---|
| "Too simple to test" | Simple code has bugs too. Testing takes 30 seconds. |
| "I'll add tests later" | Tests written afterward pass immediately—and passing immediately proves nothing. It may test the wrong thing, test the implementation instead of the behavior, or miss the edge case you forgot. You never watched it fail, so you never proved it can catch a bug. Writing the test first forces you to see that failure. |
| "Adding tests afterward achieves the same purpose (what matters is the spirit, not the ritual)" | Tests written afterward answer "what does this do?"; tests written first answer "what should this do?" Tests written afterward are already biased by the code you wrote—you verify the cases youremember, not the ones you should havediscovered. Coverage, but no proof that the tests are effective. |
| "Already tested manually" | Manual testing is ad hoc: there's no record of what you covered, it can't be rerun once the code changes, and it's very easy to miss cases under pressure. "It was fine when I tried it" ≠ thorough. Automated tests run the same way every time. |
| "Deleting X hours of work is too wasteful" | Sunk cost fallacy—that time is already spent either way. The real choice is: rewrite with TDD (high confidence) vs keep it and add tests afterward (low confidence, very likely buggy). Keeping code you can't trust is the real waste. |
| "Keep it for reference, then write the tests first" | You'll adapt it. That's adding tests afterward. Deleting is deleting. |
| "Need to explore first" | Fine. Once you're done exploring, throw it away and start with TDD. |
| "Hard to test = unclear design" | Listen to the test. Hard to test = hard to use. |
| "TDD slows me down" | TDD It isthe pragmatic path: it catches bugs before commit, prevents regressions, and lets you refactor without fear. So-called "pragmatic" shortcuts amount to debugging in production—slower, not faster. |
| "Manual testing is faster" | Manual testing cannot prove edge cases. You have to retest every time you make a change. |
| "The existing code has no tests" | You are improving it. Add tests for the existing code. |
Red flags - stop and start over
- Wrote the code first, then wrote the tests
- Only added tests after finishing the implementation
- The test passes immediately
- Cannot explain why the test fails
- "I'll add tests later"
- Convincing yourself "just this once"
- "I already tested it manually"
- "Adding tests afterward achieves the same goal"
- "What matters is the spirit, not the ritual"
- "Keep it for reference" or "adapt the existing code"
- "I've already spent X hours on it, deleting it would be a waste"
- "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: An 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 complete:
- Every new function/method has tests
- 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)
- Edge cases and error scenarios are covered
Can't 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. |
| 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.
Final rule
生产代码 → 测试存在且先失败
否则 → 不是 TDD
No exceptions without your human partner's permission.