TDD (Test-Driven Development) writes tests before code in a red-green-refactor cycle. BDD (Behavior-Driven Development) extends TDD with natural language specifications focusing on behavior from user's perspective. TDD is developer-focused; BDD involves stakeholders.
TDD Process:
TDD Benefits:
BDD Process:
Key Differences:
// TDD: Red -> Green -> Refactor
// Step 1: RED - Write failing test first
describe('ShoppingCart', () => {
test('adds item to empty cart', () => {
const cart = new ShoppingCart();
cart.addItem({ id: 1, name: 'Widget', price: 10 });
expect(cart.items).toHaveLength(1);
expect(cart.total).toBe(10);
});
});
// Test fails - ShoppingCart doesn't exist
// Step 2: GREEN - Minimal code to pass
class ShoppingCart {
constructor() {
this.items = [];
}
get total() {
return this.items.reduce((sum, item) => sum + item.price, 0);
}
addItem(item) {
this.items.push(item);
}
}
// Test passes!
// Step 3: REFACTOR - Improve while tests pass
// Add more tests, refine implementation
test('increases quantity for existing item', () => {
const cart = new ShoppingCart();
cart.addItem({ id: 1, name: 'Widget', price: 10 });
cart.addItem({ id: 1, name: 'Widget', price: 10 });
expect(cart.items).toHaveLength(1);
expect(cart.items[0].quantity).toBe(2);
});
// RED - need to update implementation...