Jest Mastery
Jest changed the JavaScript testing landscape by bundling everything (runner, assertions, mocks, coverage) into one package with a great developer experience.Why Jest?:
- Speed: Parallel execution with isolated processes.
- Snapshots: “Free” regression testing for large objects/UI.
- Mocking: Best-in-class module mocking system.
1. Mocking Strategies (The Hard Part)
Jest’s strongest feature is its ability to mock dependencies out of existence.jest.fn() vs jest.spyOn()
jest.fn(): Creates a completely new mock function.jest.spyOn(): Wraps an existing method. Preferred because it can be restored.
Module Mocking (jest.mock)
This is magic. It hoists the mock to the top of the file and replaces the require/import.
Manual Mocks (__mocks__)
For complex libraries, define the mock in a file __mocks__/fs.js (next to node_modules). Jest will automatically use this file instead of the real node module if you call jest.mock('fs').
2. Advanced Snapshots
Snapshots are great, but they can include volatile data (Timestamps, IDs) that break tests.Property Matchers
Tell Jest: “I expect a Date here, but I don’t care which date.”Inline Snapshots
Writes the snapshot inside your test file using Prettier. Good for valid small outputs.3. Timer Mocking (Fake Timers)
Jest allows you to fast-forward time, handle intervals, and debounce.Date.now().
4. Test Environment & Setup
Jest runs in Node, but creates a simulated browser environment usingjsdom.
Environment Configuration
If you differ per project:Setup Files
UsesetupFilesAfterEnv to configure global settings (like extending matchers) before tests run.
5. React Integration Patterns
Jest + React Testing Library (RTL) is the standard.Custom Render Wrapper
If your app uses Providers (Redux, Theme, Auth), genericrender will fail. Create a custom render:
render from test-utils and tests automatically have context!
Asynchronous UI
Wait for elements to appear.6. Monorepo Support
Jest is great for monorepos through theprojects key.
jest runs both. Running jest --selectProjects backend runs only one.
7. Debugging & Performance
Debugging with VS Code
Add this to.vscode/launch.json:
runInBand (serial execution) is required for breakpoints to work reliably.
Memory Leaks
Jest leaks memory. If your CI crashes on large suites:- Run with
--logHeapUsageto identify leaks. - Use
--workerIdleMemoryLimit=512MBto restart workers when they get bloated.
8. Common Pitfalls & Debugging
Implicit Globals
Implicit Globals
Symptom:
ReferenceError: expect is not defined.
Cause: Using a library that assumes Jest globals are present, but your ESLint/TSConfig doesn’t know about them.
Fix: Install @types/jest and add "types": ["jest"] to tsconfig.json.Open Handles
Open Handles
Symptom:
Jest did not exit one second after the test run has completed.
Cause: You left a database connection or server listener open.
Fix: Always close resources in afterAll(). Use jest --detectOpenHandles to find the culprit.Mock Pollution
Mock Pollution
Symptom: Test A passes. Test B fails. Running Test B alone passes.
Cause: A mock set in Test A wasn’t cleared.
Fix: Set
clearMocks: true in jest.config.js to automatically clear call counts between tests.9. Interview Questions
How does Jest achieve parallelization?
How does Jest achieve parallelization?
Jest uses a Runner that spawns multiple Node.js Worker Processes.
- The main process reads the config and orchestrates the run.
- It assigns test files (
.spec.js) to workers. - Each worker runs in its own isolated memory space. This prevents tests from interfering with each other’s global state but adds memory overhead.
Explain the difference between `jest.fn()`, `jest.mock()`, and `jest.spyOn()`.
Explain the difference between `jest.fn()`, `jest.mock()`, and `jest.spyOn()`.
jest.fn(): Creates a standalone mock function. Good for callbacks.jest.mock(): Automatically replaces an entire module (e.g.,axios) with auto-mocked versions of its exports.jest.spyOn(): Wraps an existing method on an object. Allows you to track calls while optionally keeping the original implementation.
What is Snapshot Testing and when should you avoid it?
What is Snapshot Testing and when should you avoid it?
Snapshot testing serializes a JS object/React tree to a string and compares it to a stored file.
Avoid it for:
- Highly volatile UI (timestamps, random IDs).
- As a replacement for specific assertions (Don’t just snapshot a huge object; assert
user.isAdminexplicitly if that’s what matters).