Today's Objective
By the end of this lesson you will understand unit testing with jest deeply enough to apply it immediately in real projects.
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');
});
Exercise: Write 10 Unit Tests
- Create a string utils module (capitalize, truncate, slugify)
- Write one test for each function
- Add an edge case test (empty string, null input)
- Run jest --watch and fix failures in real time
- Check coverage with jest --coverage
Day 1 Summary
- describe groups related tests
- test/it defines a single test case
- expect().toBe() checks strict equality
- jest.mock() replaces a module with a fake
- mockResolvedValue() mocks async functions
← Back
Software Testing in 5 Days Overview
Next →
Testing React Components
What's Next
The foundations from today carry directly into Day 2. In the next session the focus shifts to Day 2 — building directly on everything covered here.
Supporting Videos & Reading
Go deeper with these external references.
Day 1 Checkpoint
Before moving on, verify you can answer these without looking:
- What is the core concept introduced in this lesson, and why does it matter?
- What are the two or three most common mistakes practitioners make with this topic?
- Can you explain the key code pattern from this lesson to a colleague in plain language?
- What would break first if you skipped the safeguards or best practices described here?
- How does today's topic connect to what comes in Day 2?
Live Bootcamp
Learn this in person — 2 days, 5 cities
Thu–Fri sessions in Denver, Los Angeles, New York, Chicago, and Dallas. $1,490 per seat. June–October 2026.
Reserve Your Seat →
→