Day 62

Unit Testing

12 min
JavaScript 100 Days

Unit testing mein code ki sabse chhoti units (functions, classes) ko independently test karte hain. Good unit tests bugs early pakadti hain aur refactoring safe karti hain.

Testing a Class

Class methods aur state test karo.

bankaccount.test.js
javascript
class BankAccount {
  constructor(initialBalance = 0) {
    if (initialBalance < 0) throw new Error("Negative balance not allowed");
    this.balance = initialBalance;
    this.transactions = [];
  }
  
  deposit(amount) {
    if (amount <= 0) throw new Error("Deposit amount must be positive");
    this.balance += amount;
    this.transactions.push({ type: "deposit", amount });
  }
  
  withdraw(amount) {
    if (amount > this.balance) throw new Error("Insufficient funds");
    this.balance -= amount;
    this.transactions.push({ type: "withdrawal", amount });
  }
}

// Test file
describe("BankAccount", () => {
  let account;
  
  beforeEach(() => {
    account = new BankAccount(1000); // fresh account before each test
  });
  
  test("creates account with initial balance", () => {
    expect(account.balance).toBe(1000);
  });
  
  test("deposit increases balance", () => {
    account.deposit(500);
    expect(account.balance).toBe(1500);
  });
  
  test("withdraw decreases balance", () => {
    account.withdraw(300);
    expect(account.balance).toBe(700);
  });
  
  test("withdraw more than balance throws", () => {
    expect(() => account.withdraw(2000)).toThrow("Insufficient funds");
  });
  
  test("records transaction history", () => {
    account.deposit(200);
    account.withdraw(100);
    expect(account.transactions).toHaveLength(2);
  });
});

🎯 Practice Challenge

ShoppingCart class banao. 15+ unit tests likho — add, remove, total, discount, empty cart edge cases.