Test-Driven Development (TDD)
In one line
TDD means writing the test first, watching it fail (red), writing code to pass it (green), then improving the code (refactor).
In simple words
TDD flips the normal workflow. Instead of writing code and then testing it, you write the test first. This sounds backwards, but it's powerful.
The cycle has three steps:
- Red: Write a test for the behavior you want. Run it — it fails because the code doesn't exist yet.
- Green: Write the simplest code that makes the test pass. Don't over-engineer.
- Refactor: Improve the code's structure and readability. The tests protect you — if you break something, a test fails.
Writing tests first forces you to think about the interface and behavior before implementation. This leads to better-designed, more testable code. You also get immediate feedback and a growing suite of tests that document the expected behavior.
Example
// RED: Write failing test
test('fizzbuzz returns Fizz for 3', () => {
expect(fizzbuzz(3)).toBe('Fizz');
});
// Run: fails (fizzbuzz doesn't exist)
// GREEN: Write minimal code
function fizzbuzz(n) {
if (n % 3 === 0) return 'Fizz';
return String(n);
}
// Run: passes
// REFACTOR: improve if neededThe TDD cycle: write a failing test, implement minimally, then refactor.
Common confusions
Confused with: BDD
The difference: TDD is a coding practice (test-first); BDD focuses on describing behavior in natural language for all stakeholders.
Related terms
Related Resources
Related Lessons
- Test-Driven Development
The TDD workflow.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.