2. Jest: Matchers, Assertions, and Test Structure
Jest is the most popular JavaScript testing framework. It's fast, feature-rich, and works with everything from React to Node.js. Understanding Jest's matchers and assertions is essential for writing effective tests. This module covers Jest's core features: test structure, matchers, and assertions.
The key insight is that Jest's matchers are the building blocks of your tests. Each matcher checks a specific condition. Combining matchers creates expressive, readable tests. Understanding the full range of matchers helps you write better tests with fewer false positives.
This module covers Jest's test structure, common matchers, and advanced assertions.
Jest Test Structure
A Jest test file follows a clear structure. The test function defines a test case. The describe function groups related tests. The expect function asserts conditions. Matchers are the functions that check values. The basic pattern: given some input, perform an action, and assert the expected output. This Arrange-Act-Assert pattern is the foundation of all tests.
Jest also provides beforeAll, beforeEach, afterEach, and afterAll hooks for setup and teardown. These hooks run before or after tests, keeping your tests clean and reducing duplication. Understanding test structure is essential for writing maintainable tests.
Common Matchers
Jest provides a rich set of matchers. toBe checks exact equality (using Object.is). toEqual checks deep equality (structural equality). toBeTruthy and toBeFalsy check truthiness. toContain checks if an array or string contains a value. toThrow checks if a function throws an error. toHaveLength checks array or string length. toMatch checks string against a regex. These matchers cover most testing scenarios.
Understanding when to use each matcher is essential. Use toBe for primitives, toEqual for objects and arrays. Use toContain for checking array membership. Use toThrow for error testing. The right matcher makes your tests more readable and reliable.
// Jest test structure describe('Math functions', () => { test('adds 1 + 2 to equal 3', () => { // Arrange const a = 1; const b = 2; // Act const result = add(a, b); // Assert expect(result).toBe(3); }); test('adds negative numbers correctly', () => { expect(add(-1, -2)).toBe(-3); }); }); // Common matchers // toBe - exact equality (Object.is) expect(2 + 2).toBe(4); // toEqual - deep equality expect({ name: 'Alice' }).toEqual({ name: 'Alice' }); // toBeTruthy / toBeFalsy expect(true).toBeTruthy(); expect(false).toBeFalsy(); // toContain - array/string membership expect(['apple', 'banana']).toContain('apple'); expect('Hello World').toContain('World'); // toThrow - function throws error expect(() => { throw new Error('fail'); }).toThrow('fail'); // toMatch - regex matching expect('Hello World').toMatch(/World/); // toHaveLength - length checking expect([1, 2, 3]).toHaveLength(3);
Try It Yourself: Writing Jest Tests
Follow these steps to practice writing Jest tests with various matchers.
Step 1: Create a projectmkdir jest-matchers<br>cd jest-matchers<br>npm init -y<br>npm install --save-dev jest
Step 2: Create the code to test
Create utils.js:function add(a, b) { return a + b; }<br>function subtract(a, b) { return a - b; }<br>function multiply(a, b) { return a * b; }<br>function divide(a, b) { if (b === 0) throw new Error(<strong><code>Division by zero); return a / b; }
function getFullName(user) { return `${user.firstName} ${user.lastName}`; }
function getFruits() { return [apple, banana, orange]; }
module.exports = { add, subtract, multiply, divide, getFullName, getFruits };
Step 3: Create the test file
Create utils.test.js:const { add, subtract, multiply, divide, getFullName, getFruits } = require(<strong><code>./utils);
describe(Math functions, () => {
test(adds correctly, () => {
expect(add(2, 3)).toBe(5);
expect(add(-1, 1)).toBe(0);
});
test(subtracts correctly, () => {
expect(subtract(5, 3)).toBe(2);
expect(subtract(1, 5)).toBe(-4);
});
test(multiplies correctly, () => {
expect(multiply(2, 3)).toBe(6);
expect(multiply(0, 5)).toBe(0);
});
test(divides correctly, () => {
expect(divide(6, 2)).toBe(3);
expect(divide(1, 3)).toBeCloseTo(0.333, 3);
});
test(throws on division by zero, () => {
expect(() => divide(1, 0)).toThrow(Division by zero);
});
});
describe(Object functions, () => {
test(gets full name correctly, () => {
const user = { firstName: Alice, lastName: Smith };
expect(getFullName(user)).toBe(Alice Smith);
});
test(handles missing last name, () => {
const user = { firstName: Bob };
expect(getFullName(user)).toBe(Bob undefined);
});
});
describe(Array functions, () => {
test(returns fruits array, () => {
const fruits = getFruits();
expect(fruits).toContain(apple);
expect(fruits).toHaveLength(3);
expect(fruits).toEqual([apple, banana, orange]);
});
});
Step 4: Run the testsnpx jest
Try It Yourself: Add a function that sorts an array. Write tests for it. Add a function that calculates the average of an array. Write tests for it.
Knowledge Check
Ready to test your understanding of 2. Jest: Matchers, Assertions, and Test Structure?