Testing JavaScript Code with Jest

Jest has been the default JavaScript testing framework for years — zero-config for most projects, with built-in mocking, assertions, and coverage reporting.

import { Cart } from './cart.js';

describe('Cart', () => {
    test('adding an item increases the total', () => {
        const cart = new Cart();
        cart.add({ name: 'Widget', price: 9.99 }, 2);
        expect(cart.getTotal()).toBe(19.98);
    });

    test('empty cart has a zero total', () => {
        expect(new Cart().getTotal()).toBe(0);
    });
});

// Mocking a dependency
jest.mock('./paymentService.js');
test('checkout calls the payment service', () => {
    const cart = new Cart();
    cart.checkout();
    expect(paymentService.charge).toHaveBeenCalledWith(cart.getTotal());
});
npx jest
npx jest --coverage
npx jest --watch

Jest’s built-in mocking (jest.mock()) auto-mocks an entire module, letting you test a unit in isolation without its real dependencies actually running — essential for testing code that talks to a database or an external API.