Mocking Strategies with jest.mock and spyOn
Intermediatev1.0.0
Master Jest mocking — learn when to use jest.mock, jest.spyOn, and manual mocks to isolate units under test while keeping tests maintainable and meaningful.
Content
Overview
Mocking is the most powerful — and most misused — feature of Jest. The right mocking strategy isolates the unit under test while keeping tests meaningful. The wrong strategy creates tests that verify mocks instead of code.
Why This Matters
- -Isolation — test one module without its dependencies
- -Speed — avoid real database, network, and file system calls
- -Determinism — control external inputs for predictable tests
- -Focus — verify specific interactions and side effects
How It Works
jest.mock() — Replace Entire Modules
jest.spyOn() — Partial Mocking
Manual Mocks — Complex Module Replacements
Mock Implementations
Best Practices
- -Mock at module boundaries (API clients, databases) not internal helpers
- -Use
jest.spyOnwhen you need to keep the original implementation available - -Always call
mockRestore()or usejest.restoreAllMocks()inafterEach - -Prefer
mockResolvedValueovermockImplementation(() => Promise.resolve()) - -Use
jest.mocked()for type-safe mock access in TypeScript - -Verify mock calls with
toHaveBeenCalledWithfor interaction testing
Common Mistakes
- -Mocking the module under test (you should test it, not mock it)
- -Forgetting to restore mocks — leaks between tests
- -Over-mocking: if everything is mocked, the test verifies nothing
- -Using
jest.fn()without specifying return values (returns undefined) - -Not clearing mocks between tests (
jest.clearAllMocks()inafterEach)
FAQ
Discussion
Loading comments...