9. Test-Driven Development (TDD): Red-Green-Refactor
Test-Driven Development (TDD) is a software development practice where you write tests before code. The red-green-refactor cycle is the heart of TDD: write a failing test (red), write the minimal code to make it pass (green), then refactor while keeping tests green. TDD leads to better code design, higher test coverage, and fewer bugs.
The key insight is that TDD is a design practice, not just a testing practice. Writing tests first forces you to think about the API and design before implementation. It results in more testable, modular code. Understanding TDD is essential for professional software development.
This module covers the TDD cycle, benefits, and practical examples.
Red: Write a Failing Test
The first step of TDD is writing a failing test. The test should describe a behavior you want to implement. It should fail because the code doesn't exist yet. This step forces you to think about the API and requirements before writing code.
Writing the test first clarifies what you're building. It prevents over-engineering and ensures you only build what's needed. The test becomes the specification for the code.
Green: Make the Test Pass
The second step is writing the minimal code to make the test pass. Don't over-engineer. Write the simplest code that works. This step gets you to green as quickly as possible. Once the test passes, you can refactor.
Writing minimal code helps you avoid premature optimization. It keeps your code focused on the requirements. It also makes it easier to refactor because you have working code.
Refactor: Improve the Code
The third step is refactoring. With passing tests, you can safely improve the code. Refactoring includes: renaming variables, extracting functions, removing duplication, and improving design. The tests ensure you don't break anything.
Refactoring is where you pay down technical debt. It keeps your code clean and maintainable. The safety net of tests gives you confidence to refactor aggressively.
// Step 1: RED - Write a failing test // calculator.test.js import { Calculator } from './calculator'; describe('Calculator', () => { test('adds two numbers', () => { const calc = new Calculator(); expect(calc.add(2, 3)).toBe(5); }); test('subtracts two numbers', () => { const calc = new Calculator(); expect(calc.subtract(5, 3)).toBe(2); }); test('multiplies two numbers', () => { const calc = new Calculator(); expect(calc.multiply(2, 3)).toBe(6); }); }); // Step 2: GREEN - Write minimal code to pass // calculator.js export class Calculator { add(a, b) { return a + b; } subtract(a, b) { return a - b; } multiply(a, b) { return a * b; } } // Step 3: REFACTOR - Improve the code // calculator.js export class Calculator { constructor() { this.operations = { add: (a, b) => a + b, subtract: (a, b) => a - b, multiply: (a, b) => a * b, }; } add(a, b) { return this.operations.add(a, b); } subtract(a, b) { return this.operations.subtract(a, b); } multiply(a, b) { return this.operations.multiply(a, b); } } // The refactored code is more maintainable // And the tests still pass!
Try It Yourself: TDD Exercise
Follow these steps to practice TDD.
Exercise: Build a shopping cart
Step 1: Write a test for adding items// cart.test.js<br>import { ShoppingCart } from <strong><code>./cart;
describe(ShoppingCart, () => {
test(adds an item to the cart, () => {
const cart = new ShoppingCart();
cart.addItem(apple, 1.99, 2);
expect(cart.getTotal()).toBe(3.98);
});
});
Step 2: Make it pass// cart.js<br>export class ShoppingCart {<br> constructor() {<br> this.items = [];<br> }<br><br> addItem(name, price, quantity) {<br> this.items.push({ name, price, quantity });<br> }<br><br> getTotal() {<br> return this.items.reduce((sum, item) => sum + item.price * item.quantity, 0);<br> }<br>}
Step 3: Write a test for removing itemstest(<strong><code>removes an item from the cart, () => {
const cart = new ShoppingCart();
cart.addItem(apple, 1.99, 2);
cart.removeItem(apple);
expect(cart.getTotal()).toBe(0);
});
Step 4: Make it passremoveItem(name) {<br> this.items = this.items.filter(item => item.name !== name);<br>}
Step 5: Refactor
Extract the total calculation into a method. Remove duplication.
Try It Yourself: Continue TDD to add features: apply discount, apply tax, get item count.
Knowledge Check
Ready to test your understanding of 9. Test-Driven Development (TDD): Red-Green-Refactor?