Test-Driven Development
Writing tests before code sounds backward, right? I definitely thought so when I first heard about it. But TDD is actually a really clean way to build things. Let me walk you through how it works.
The idea is simple. You write the test first, watch it fail, write the minimum code to make it pass, then clean up. That is the red-green-refactor cycle.
Red - Write a Failing Test
Start by writing a test for the behavior you want. It will fail because the function does not exist yet.
test('returns absolute value of a number', () => {
expect(abs(-5)).toBe(5);
expect(abs(3)).toBe(3);
expect(abs(0)).toBe(0);
});
Run the test. It fails. Good. That is exactly what should happen.
Green - Write Minimum Code
Now write the simplest code that makes the test pass. Do not overthink it.
function abs(n) {
if (n < 0) return -n;
return n;
}
Run the test again. It passes. You are done with this step. Even if the code looks too simple, that is fine.
Refactor - Clean Up
Now you can clean up the code without changing its behavior. Maybe you simplify the function, improve naming, or remove duplication.
function abs(n) {
return n < 0 ? -n : n;
}
Run the test one more time. Still passes. Now you have clean code with a test that proves it works.
Why Bother?
TDD forces you to think about what you want before you build it. It catches design problems early. It gives you tests as a side effect. And it prevents over-engineering because you only write enough code to pass the test.
Try it Yourself →Key Takeaways
- TDD follows the red-green-refactor cycle
- Write a failing test first to define the behavior
- Write the minimum code to make the test pass
- Refactor the code now that you have a safety net
- TDD helps you design better and avoid over-engineering