Advanced Unit Testing Patterns
What you'll build
A comprehensive test suite for a string utility module using parameterized tests, custom matchers, and beforeEach/afterEach hooks for clean test isolation.
Goals
- Write parameterized/data-driven tests
- Create custom Jest/Vitest matchers
- Use setup and teardown hooks effectively
- Test edge cases and boundary conditions
Prerequisites
- Basic test syntax (describe, it, expect)
- Assertions and matchers
- JavaScript/TypeScript functions
Steps
- 1
Create the utility module
Create a string utility module with functions to test: capitalize, truncate, slugify, and camelCase.
Code// src/utils/stringUtils.ts export function capitalize(s: string): string { if (!s) return s; return s[0].toUpperCase() + s.slice(1).toLowerCase(); } export function truncate(s: string, max: number): string { if (s.length <= max) return s; return s.slice(0, max - 3) + '...'; } export function slugify(s: string): string { return s.toLowerCase().trim().replace(/[^\w\s-]/g, '').replace(/[\s_-]+/g, '-'); } export function camelCase(s: string): string { return s.replace(/[^\w]+(.)/g, (_, c) => c.toUpperCase()); }Expected result
Four utility functions exported and ready to test.
- 2
Write parameterized tests
Use it.each to run the same test with multiple inputs. This avoids duplicating test code for similar assertions.
Codeimport { capitalize, slugify } from '../utils/stringUtils'; describe('capitalize', () => { it.each([ ['hello', 'Hello'], ['HELLO', 'Hello'], ['h', 'H'], ['', ''], ])('capitalize(%j) === %j', (input, expected) => { expect(capitalize(input)).toBe(expected); }); }); describe('slugify', () => { it.each([ ['Hello World', 'hello-world'], [' Multiple Spaces ', 'multiple-spaces'], ['Special!@#Chars', 'specialchars'], ])('slugify(%j) === %j', (input, expected) => { expect(slugify(input)).toBe(expected); }); });Expected result
All parameterized cases pass — one test definition covers many inputs.
- 3
Create a custom matcher
Extend expect with a custom matcher toBeWithinRange that checks if a number is within a range. Custom matchers make domain-specific assertions readable.
Codeexpect.extend({ toBeWithinRange(received: number, floor: number, ceiling: number) { const pass = received >= floor && received <= ceiling; return { pass, message: () => pass ? `expected ${received} not to be within range [${floor}, ${ceiling}]` : `expected ${received} to be within range [${floor}, ${ceiling}]`, }; }, }); // Usage it('truncate length is within bounds', () => { const result = truncate('a very long string here', 10); expect(result.length).toBeWithinRange(0, 10); });Expected result
The custom matcher works and produces a clear failure message.
- 4
Use setup and teardown hooks
Use beforeEach and afterEach to set up and clean up test state. This is essential for tests that share setup logic or modify global state.
Codedescribe('with mock console', () => { let mockLog: jest.Mock; beforeEach(() => { mockLog = jest.spyOn(console, 'log').mockImplementation(); }); afterEach(() => { mockLog.mockRestore(); }); it('does not log on normal operation', () => { capitalize('test'); expect(mockLog).not.toHaveBeenCalled(); }); });Expected result
console.log is mocked for each test and restored after — no side effects between tests.
- 5
Test boundary conditions
Systematically test edge cases: empty strings, single characters, very long strings, and unicode characters. Boundary testing catches off-by-one and encoding bugs.
Codedescribe('boundary conditions', () => { it('handles empty string', () => { expect(capitalize('')).toBe(''); expect(truncate('', 10)).toBe(''); expect(slugify('')).toBe(''); }); it('handles single character', () => { expect(capitalize('x')).toBe('X'); }); it('handles unicode', () => { expect(capitalize('über')).toBe('Über'); expect(slugify('café au lait')).toBe('caf-au-lait'); }); it('truncate at exact boundary', () => { expect(truncate('12345678', 8)).toBe('12345678'); expect(truncate('123456789', 8)).toBe('12345...'); }); });Expected result
All boundary cases pass, confirming the functions handle edge inputs correctly.
Try it yourself
import { capitalize } from '../utils/stringUtils';
describe('capitalize', () => {
// TODO: write parameterized tests
});import { capitalize, slugify, truncate, camelCase } from '../utils/stringUtils';
describe('capitalize', () => {
it.each([['hello', 'Hello'], ['', '']])('capitalize(%j) === %j', (i, e) => {
expect(capitalize(i)).toBe(e);
});
});What you learned
You mastered advanced testing patterns — parameterized tests for coverage, custom matchers for readability, hooks for isolation, and boundary testing for robustness. These techniques scale to large test suites.
Related Resources
Related Lessons
- Unit Testing
Testing individual units.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.