Day 61

Testing — Jest Basics

13 min
JavaScript 100 Days

Testing code ki quality ensure karta hai. Jest JavaScript ka most popular testing framework hai — React, Next.js — sab Jest use karte hain. Professional developer banna hai to testing aani chahiye.

Jest Setup & First Test

Jest install karo aur pehla test likho.

math.test.js
javascript
// npm install --save-dev jest
// package.json: "test": "jest"

// math.js — function to test
function add(a, b) { return a + b; }
function multiply(a, b) { return a * b; }
function divide(a, b) {
  if (b === 0) throw new Error("Cannot divide by zero");
  return a / b;
}
module.exports = { add, multiply, divide };

// math.test.js — test file
const { add, multiply, divide } = require("./math");

// describe — group related tests
describe("Math functions", () => {
  test("add 2 + 3 equals 5", () => {
    expect(add(2, 3)).toBe(5);
  });
  
  test("multiply 4 * 5 equals 20", () => {
    expect(multiply(4, 5)).toBe(20);
  });
  
  test("divide by zero throws error", () => {
    expect(() => divide(10, 0)).toThrow("Cannot divide by zero");
  });
  
  test("add negative numbers", () => {
    expect(add(-1, -2)).toBe(-3);
  });
});

// Run: npm test

Common Matchers

Jest matchers se different assertions karo.

matchers.js
javascript
// Numbers
expect(2 + 2).toBe(4);           // exact equality
expect(2.1 + 1.9).toBeCloseTo(4); // floating point

// Strings
expect("hello world").toContain("world");
expect("Zohaib").toMatch(/^Z/);   // regex

// Arrays
expect([1,2,3]).toContain(2);
expect([1,2,3]).toHaveLength(3);

// Objects
expect({name: "Ali"}).toEqual({name: "Ali"}); // deep equal
expect({name: "Ali", age: 25}).toMatchObject({name: "Ali"});

// Truthiness
expect(null).toBeNull();
expect(undefined).toBeUndefined();
expect("value").toBeTruthy();
expect(0).toBeFalsy();

// Async
test("async test", async () => {
  const data = await fetchUser(1);
  expect(data.id).toBe(1);
});

🎯 Practice Challenge

calculateGrade(score) function banao. 10 test cases likho — edge cases bhi (0, 100, negative, strings).