Unit Tests for Pure Functions and Hooks
What you'll learn: How to test custom hooks, utility functions, and pure business logic in isolation without the overhead of browser environments or full component trees.
The Isolation Advantage
While E2E tests validate entire user flows through a real browser, unit tests shine when testing the building blocks of your application. Pure functions (like formatters, validators, calculators) and custom hooks (like useDebounce, useLocalStorage) contain focused logic that doesn't need the complexity of browser rendering.
Think of it like testing a car engine on a test bench instead of driving the whole car. You get faster feedback, pinpoint failures precisely, and can test edge cases that would be expensive to recreate in a full E2E scenario.
What to Unit Test
Pure functions are perfect candidates:
formatCurrency(1234.5)→"$1,234.50"validateEmail(email)→true/falsecalculateDiscount(price, percentage)
Custom hooks with isolated logic:
usePagination(items, pageSize)useToggle(initialValue)useDebounce(value, delay)
These tests run in milliseconds (no browser startup), can run thousands of times in CI without timeout concerns, and provide the fast feedback loop that developers rely on during active coding.
The Sweet Spot
You've already learned renderHook() for testing hooks and behavior-focused testing for components. Unit tests complement your E2E suite by covering:
- Edge cases (empty arrays, null values, boundary conditions)
- Pure logic (math, formatting, parsing)
- Reusable utilities (date helpers, string manipulation)
Leave the "does this button navigate correctly" testing to E2E. Use unit tests for "does this function return the right value for 50 different inputs."
Key Takeaway: Unit test pure functions and hooks in isolation for fast, focused feedback on business logic—reserve E2E tests for validating complete user journeys through the browser.