Unit tests with Jest
The easiest code to test is code with no side effects. A pure function takes input and returns output without touching the database, the file system, or the network. Your service layer should be mostly pure when you can help it, and tests against pure functions are the cheapest coverage you will ever write.
import { describe, it, expect } from '@jest/globals';
import { formatBookTitle } from '../src/utils/format';
describe('formatBookTitle', () => {
it('capitalizes the first letter of each word', () => {
expect(formatBookTitle('the great gatsby')).toBe('The Great Gatsby');
});
it('trims leading and trailing whitespace', () => {
expect(formatBookTitle(' hello world ')).toBe('Hello World');
});
it('handles empty strings', () => {
expect(formatBookTitle('')).toBe('');
});
});A minimal unit test. describe groups related cases, it states one expectation, expect checks a value.
Read the test top to bottom. describe is a label for a group of cases, usually one per function. it (or test) is a single case with a short name that describes the expected behavior. expect takes the actual value and chains an assertion. That is the entire Jest vocabulary you need for 90 percent of your tests.
One piece of advice that pays off for years: name test cases like sentences. 'should return the new book with a generated id' reads better than 'test case 3'. When a test fails in CI, the name is the first thing you see. Make it useful.
Quiz: Quiz
Loading practice…