What is unit testing in JavaScript with Jest?
Unit testing checks individual pieces of code in isolation. Jest is a popular all-in-one JavaScript testing framework.
Structure — describe groups tests; test (or it) defines a case; expect with matchers asserts the result.
Mocks — replace dependencies so you test one unit at a time.
Extras — built-in assertions, code coverage, and snapshot testing.
Good tests follow Arrange–Act–Assert and cover the happy path plus edge cases and errors.
// 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';
describe('Math functions', () => {
test('add returns sum of two numbers', () => {
expect(add(2, 3)).toBe(5);
expect(add(-1, 1)).toBe(0);
expect(add(0, 0)).toBe(0);
});
test('divide returns quotient', () => {
expect(divide(10, 2)).toBe(5);
expect(divide(7, 2)).toBeCloseTo(3.5); // Floating point
});
test('divide throws on zero', () => {
expect(() => divide(10, 0)).toThrow('Division by zero');
});
});
// Mocking
test('fetchUser calls API correctly', async () => {
global.fetch = jest.fn(() =>
Promise.resolve({ json: () => Promise.resolve({ name: 'John' }) })
);
const user = await fetchUser(1);
expect(fetch).toHaveBeenCalledWith('/api/users/1');
expect(user.name).toBe('John');
});
// Run: npx jest --coveragedescribe groups related tests. test defines individual test cases. expect(value).toBe(expected) asserts strict equality. toBeCloseTo handles floating-point imprecision. toThrow tests exceptions (must wrap in arrow function). jest.fn creates a mock function. toHaveBeenCalledWith verifies mock was called correctly. --coverage generates a coverage report.
Show test structure (describe/test/expect), common matchers (toBe, toEqual, toThrow), mocking (jest.fn), and coverage (--coverage). toBeCloseTo for floating-point comparison. The arrow function wrapping for toThrow is a common gotcha.