12. Testing with Jest
Why Test Your Code?
Testing prevents regressions — fixing one bug and accidentally breaking three other things. Automated tests run in milliseconds and catch bugs before they reach production. Jest is the most popular testing framework for Node.js.
What is Jest?
Jest is a testing framework created by Facebook. It works out of the box with zero configuration and includes an assertion library, mocking, and coverage reports.
const add = (a, b) => a + b; const divide = (a, b) => { if (b === 0) throw new Error('Cannot divide by zero'); return a / b; }; test('adds 1 + 2 to equal 3', () => { expect(add(1, 2)).toBe(3); }); test('throws error when dividing by zero', () => { expect(() => divide(10, 0)).toThrow('Cannot divide by zero'); });
Common Assertions
Assertions are the checks that verify your code works correctly. toBe() is for primitive values. toEqual() is for objects and arrays (deep equality). toContain() checks if an array or string contains a value.
test('Common assertions', () => { expect(2 + 2).toBe(4); expect({ name: 'John' }).toEqual({ name: 'John' }); expect(null).toBeFalsy(); expect(5).toBeGreaterThan(3); expect('hello world').toContain('world'); expect([1, 2, 3]).toContain(2); });
Grouping Tests with describe
describe() blocks group related tests together. This keeps your test files organized. You can nest describes for even more organization.
describe('Math Utilities', () => { describe('add()', () => { test('adds positive numbers', () => { expect(add(2, 3)).toBe(5); }); test('adds negative numbers', () => { expect(add(-1, -2)).toBe(-3); }); }); describe('divide()', () => { test('divides correctly', () => { expect(divide(10, 2)).toBe(5); }); test('throws on zero', () => { expect(() => divide(10, 0)).toThrow(); }); }); });
Setup and Teardown (beforeEach)
beforeEach() runs before each test. This ensures each test starts with a clean, predictable state. afterEach() runs after each test for cleanup.
let database = []; beforeEach(() => { database = []; database.push({ id: 1, name: 'Default' }); }); test('adds a user', () => { database.push({ id: 2, name: 'Alice' }); expect(database.length).toBe(2); }); test('starts with default user', () => { expect(database.length).toBe(1); // Reset by beforeEach });
Mocking Functions
Mocking replaces real functions with fake ones you control. This isolates the code you're testing. You don't want to actually send emails or make API calls during tests.
const sendEmail = jest.fn(); function registerUser(email) { sendEmail(email, 'Welcome!'); return { success: true }; } test('sends welcome email', () => { registerUser('test@test.com'); expect(sendEmail).toHaveBeenCalledTimes(1); expect(sendEmail).toHaveBeenCalledWith('test@test.com', 'Welcome!'); });
Testing Express APIs with Supertest
Supertest allows you to test HTTP endpoints without actually binding to a network port. It makes requests to your Express app and returns promises.
const request = require('supertest'); const app = require('../app'); describe('User API', () => { test('GET /api/users returns 200', async () => { const response = await request(app) .get('/api/users') .expect(200); expect(Array.isArray(response.body)).toBe(true); }); test('POST /api/users creates user', async () => { const newUser = { name: 'Alice', email: 'alice@test.com' }; const response = await request(app) .post('/api/users') .send(newUser) .expect(201); expect(response.body.name).toBe('Alice'); }); });
Knowledge Check
Ready to test your understanding of 12. Testing with Jest?