Classic JS Tutorial | JS in VS 2026 | JS Examples | jQuery
⚡ Lesson 29 of 30

Testing with Jest

Write, run, and organise automated unit tests using Jest inside Visual Studio 2026.

Setup

Install Jest and configure it:

npm install --save-dev jest

# package.json
{
  "scripts": { "test": "jest" },
  "jest": {
    "testEnvironment": "node",
    "transform": {}
  }
}

# Run tests
npm test
npm test -- --watch  // re-run on save

Your First Test

Create math.test.js next to math.js:

// math.js
export function add(a, b) { return a + b; }
export function divide(a, b) {
  if (b === 0) throw new Error("Division by zero");
  return a / b;
}

// math.test.js
import { add, divide } from "./math.js";

test("adds two numbers", () => {
  expect(add(2, 3)).toBe(5);
  expect(add(-1, 1)).toBe(0);
});

test("throws on division by zero", () => {
  expect(() => divide(1, 0)).toThrow("Division by zero");
});

Matchers

Jest provides many built-in matchers:

expect(value).toBe(5);              // strict equal
expect(obj).toEqual({ a:1 });       // deep equal
expect(arr).toContain("item");      // array contains
expect(str).toMatch(/pattern/);     // regex match
expect(val).toBeTruthy();
expect(val).toBeNull();
expect(fn).toThrow();
expect(num).toBeGreaterThan(10);
expect(arr).toHaveLength(3);

describe & beforeEach

Group related tests and share setup code:

describe("BankAccount", () => {
  let account;

  beforeEach(() => {
    account = new BankAccount();
    account.deposit(100);
  });

  test("starts with deposited balance", () => {
    expect(account.balance).toBe(100);
  });

  test("throws on overdraft", () => {
    expect(() => account.withdraw(200)).toThrow();
  });
});

Mocking

Replace real dependencies with controllable fakes:

import { fetchUser } from "./api.js";
jest.mock("./api.js");

test("greets user by name", async () => {
  fetchUser.mockResolvedValue({ name: "Alice" });

  const result = await greetUser(1);
  expect(result).toBe("Hello, Alice!");
  expect(fetchUser).toHaveBeenCalledWith(1);
});
← Lesson 28🏠 HomeLesson 30 →