Labs ICT
โญ Pro Login

Testing with Jest

Write tests that give you confidence.

Setting Up Jest

Install Jest as a dev dependency and add a test script to your package.json.

npm install --save-dev jest

Add to package.json:

{
  "scripts": {
    "test": "jest"
  }
}

Writing Tests

Use describe to group related tests, test to define individual test cases, and expect with matchers to assert values.

// math.test.js
const { add, subtract } = require("./math");

describe("Math functions", () => {
  test("add adds two numbers", () => {
    expect(add(2, 3)).toBe(5);
  });

  test("subtract subtracts two numbers", () => {
    expect(subtract(5, 3)).toBe(2);
  });

  test("add handles negative numbers", () => {
    expect(add(-1, 1)).toBe(0);
  });
});

Jest Matchers

Jest provides many matchers for different kinds of assertions. Use toBe for strict equality, toEqual for deep equality, and others for specific checks.

expect(value).toBe(42);           // Strict equality
expect(value).toEqual({ a: 1 }); // Deep equality
expect(value).toBeTruthy();
expect(value).toBeNull();
expect(value).toContain("hello");
expect(value).toThrow(Error);
expect(value).toBeGreaterThan(5);

Testing Async Code

Use async/await in tests for asynchronous code. Use rejects.toThrow to test that a promise rejects with a specific error.

test("fetches user data", async () => {
  const user = await fetchUser(1);
  expect(user).toBeDefined();
  expect(user.name).toBe("Alice");
});

test("handles fetch error", async () => {
  await expect(fetchUser(999)).rejects.toThrow("Not found");
});
Try it Yourself โ†’

Setup and Teardown

Jest provides lifecycle functions to run code before and after tests. Use beforeAll/afterAll for one-time setup, and beforeEach/afterEach for per-test setup.

beforeAll(() => {
  // Run once before all tests
});

beforeEach(() => {
  // Run before each test
});

afterEach(() => {
  // Run after each test
});

afterAll(() => {
  // Run once after all tests
});

๐Ÿงช Quick Quiz

Which test framework is most popular for Node.js?