Unit tests verify individual functions in isolation. Jest is the most popular JavaScript test runner. Today you will write pure unit tests, use matchers, mock dependencies, and run tests in watch mode.
npm install --save-dev jest
# or for TypeScript:
npm install --save-dev jest @types/jest ts-jest// src/utils/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;
}
// src/utils/math.test.js
import { add, divide } from './math';
describe('math utils', () => {
test('adds two numbers', () => {
expect(add(2, 3)).toBe(5);
});
test('divides two numbers', () => {
expect(divide(10, 2)).toBe(5);
expect(divide(10, 2)).toBeCloseTo(5);
});
test('throws on divide by zero', () => {
expect(() => divide(10, 0)).toThrow('Division by zero');
});
});// Mocking modules
import * as api from './api';
jest.mock('./api');
test('calls the API once', async () => {
api.fetchUser.mockResolvedValue({ id: 1, name: 'Bo' });
const user = await api.fetchUser(1);
expect(api.fetchUser).toHaveBeenCalledTimes(1);
expect(api.fetchUser).toHaveBeenCalledWith(1);
expect(user.name).toBe('Bo');
});