Jest logoJest INTERMEDIATE

Jest

Complete Jest testing framework guide with matchers, mocking, async testing, and best practices for JavaScript/TypeScript

12 min read
jesttestingunit-testingmockingtddjavascripttypescriptreact

Setup & Configuration

Installing and configuring Jest for your project

Installation & Basic Setup

Setting up Jest in your JavaScript/TypeScript project

javascript
💡 Use test:watch for TDD workflow with automatic re-runs
⚡ Add coverage thresholds to enforce code quality standards
📌 Configure testMatch to find your test files correctly
🟢 Start with node environment, switch to jsdom for DOM testing
setupconfiguration

Basic Testing

Writing your first tests with Jest

Test Structure & Basics

Organizing tests with describe, it, and test blocks

javascript
💡 Use describe blocks to group related tests logically
⚡ beforeEach/afterEach run for every test, beforeAll/afterAll run once
📌 test and it are aliases - use whichever reads better
🟢 Use test.only to focus on a single test during development
basicsstructure

Matchers

Jest matchers for different types of assertions

Common Matchers

Most frequently used Jest matchers for assertions

javascript
💡 Use toEqual for objects/arrays, toBe for primitives
⚡ toBeCloseTo is essential for floating point comparisons
📌 toStrictEqual checks undefined properties and array holes
🟢 Combine matchers with .not for negative assertions
matchersassertions

Custom Matchers

Creating your own Jest matchers for domain-specific assertions

typescript
💡 Custom matchers improve test readability for domain logic
⚡ Add TypeScript definitions for autocomplete support
📌 Use setupFilesAfterEnv to load matchers globally
🟢 Asymmetric matchers allow flexible partial matching
matcherscustomadvanced

Mocking

Mocking functions, modules, and dependencies

Function Mocks

Creating and using mock functions (spies)

javascript
💡 Use mockImplementationOnce for different behavior per call
⚡ mockClear vs mockReset vs mockRestore have different scopes
📌 Access .mock property for detailed call information
🟢 jest.spyOn preserves original implementation by default
mockingfunctions

Module Mocks

Mocking entire modules and their exports

javascript
💡 Place manual mocks in __mocks__ folder adjacent to module
⚡ Use requireActual for partial mocks to keep some real code
📌 Mock hoisting moves jest.mock to top of file automatically
🟢 TypeScript: cast mocked modules for proper types
mockingmodules

Async Testing

Testing asynchronous code with promises and callbacks

Testing Promises & Async/Await

Different patterns for testing asynchronous code

javascript
💡 Always return or await promises in tests to avoid false positives
⚡ Use expect.assertions(n) to ensure async assertions run
📌 resolves/rejects matchers make async tests cleaner
🟢 Set custom timeout as third parameter for slow operations
asyncpromises

Timers & Dates

Testing code that uses setTimeout, setInterval, and Date

Fake Timers

Controlling time in tests with Jest fake timers

javascript
💡 Modern timers (default) also mock Date, legacy timers don't
⚡ Use runOnlyPendingTimers to avoid infinite timer loops
📌 Always restore real timers in afterEach to avoid test pollution
🟢 setSystemTime allows testing date-dependent logic easily
timersdatemocking

Testing React Components

Testing React components with Jest and React Testing Library

Component Testing Basics

Testing React components with React Testing Library

javascript
💡 Use userEvent over fireEvent for more realistic interactions
⚡ Create custom render function to wrap providers
📌 MSW is excellent for mocking API calls in tests
🟢 Always await user interactions with userEvent.setup()
reactcomponentstesting-library

Code Coverage

Measuring and improving test coverage

Coverage Configuration

Setting up and interpreting code coverage reports

javascript
💡 HTML coverage reports show line-by-line coverage visually
⚡ Set different thresholds for critical vs non-critical code
📌 Use istanbul ignore comments sparingly for untestable code
🟢 Coverage helps identify untested code, not test quality
coverageconfiguration

Best Practices

Testing best practices and common patterns

Testing Best Practices

Guidelines for writing maintainable and effective tests

javascript
💡 Follow AAA pattern: Arrange, Act, Assert for clarity
⚡ Test behavior and outputs, not implementation details
📌 Keep tests independent - each should run in isolation
🟢 Use descriptive test names that explain what and why
best-practicespatterns