Day 65

TDD — Test Driven Development

12 min
JavaScript 100 Days

TDD (Test Driven Development) mein pehle test likhte hain, phir code. Red (test fail) → Green (minimum code to pass) → Refactor (clean up). Yeh approach bugs reduce karta hai aur design improve karta hai.

Red-Green-Refactor

TDD cycle step by step.

tdd.js
javascript
// TDD Example: Stack data structure

// STEP 1: RED — Test likho (fail hoga)
describe("Stack", () => {
  test("starts empty", () => {
    const stack = new Stack();
    expect(stack.isEmpty()).toBe(true);
    expect(stack.size()).toBe(0);
  });
  
  test("push adds to top", () => {
    const stack = new Stack();
    stack.push(1);
    stack.push(2);
    expect(stack.size()).toBe(2);
    expect(stack.peek()).toBe(2); // top element
  });
  
  test("pop removes from top", () => {
    const stack = new Stack();
    stack.push("a");
    stack.push("b");
    expect(stack.pop()).toBe("b");
    expect(stack.size()).toBe(1);
  });
  
  test("pop on empty stack throws", () => {
    const stack = new Stack();
    expect(() => stack.pop()).toThrow("Stack is empty");
  });
});

// STEP 2: GREEN — Minimum code to pass
class Stack {
  constructor() { this.items = []; }
  isEmpty() { return this.items.length === 0; }
  size() { return this.items.length; }
  push(item) { this.items.push(item); }
  peek() { return this.items[this.items.length - 1]; }
  pop() {
    if (this.isEmpty()) throw new Error("Stack is empty");
    return this.items.pop();
  }
}

// STEP 3: REFACTOR — clean up if needed

🎯 Practice Challenge

TDD se Queue data structure banao — enqueue, dequeue, peek, isEmpty, size. Pehle saare tests likho, phir implement karo.