Unit Testing
Overview
Unit tests verify small pieces of logic in isolation.
Why It Matters
They catch regressions quickly and make behavior easier to change with confidence.
Core Concepts
- Test a single unit.
- Use clear inputs and outputs.
- Keep tests deterministic.
Mental Models
Unit tests are strongest when they describe the contract of a function or component, not its internal implementation.
Best Practices
- Test edge cases and core paths.
- Avoid brittle coupling to implementation details.
- Keep test setup small.
Common Mistakes
- Testing internals instead of behavior.
- Over-mocking everything.
- Writing tests that are hard to read.
Trade-offs
Unit tests are fast and precise, but they do not replace broader integration coverage.
Decision Framework
| Good target | Less useful target |
|---|---|
| Pure logic | Complex UI interactions only in isolation |
| Utility functions | Deep implementation details |
Examples
expect(sum(2, 3)).toBe(5);
Checklists
- Does the test verify behavior?
- Is the failure easy to understand?
- Is the test deterministic?
Senior Engineer Notes
Senior engineers keep unit tests readable because unreadable tests become a maintenance burden.