Jest Basics
Get started with Jest: configuration, test blocks, matchers, and the CLI.
What you'll learn
- How to install and configure Jest for a JavaScript or TypeScript project
- Writing describe, test, and expect with Jest matchers
- Running Jest in watch and CI modes
- Understanding Jest's module isolation and config options
Concept
Why Jest
Jest is a complete, zero-config test framework: it bundles a test runner, an assertion library, a mocking system, snapshot testing, and coverage reporting. It became the default in the React ecosystem and remains extremely common in legacy and Create React App projects. Its biggest strength is that everything works out of the box; its main drawback is speed on very large suites.
Installation and Config
Install with pnpm add -D jest (and ts-jest or @swc/jest for TypeScript). Run npx jest --init to generate a jest.config.js with sensible defaults. Key options include testEnvironment (node vs jsdom), transform for TypeScript, and moduleNameMapper to alias @ to src. Add scripts "test": "jest --watch" and "test:ci": "jest --ci".
Test Structure
Jest uses describe for groups, test (or it) for cases, and expect(value).matcher(expected) for assertions. Matchers include toBe (identity), toEqual (deep equality), toContain, toHaveLength, toThrow, and many more. beforeEach and afterEach hooks run setup and teardown around each test in a describe block.
Module Isolation
By default Jest resets the module registry between tests, which prevents state from leaking but can make tests slower. You can tune this with resetMocks, restoreMocks, and clearMocks options. Understanding this isolation model is essential when mocking modules — each test gets a fresh copy unless you configure otherwise.
In Practice
When you bootstrap Jest in a TypeScript project, choose @swc/jest over ts-jest for transform speed — SWc compiles an order of magnitude faster. Set testEnvironment per file when you mix Node and DOM tests: a jest.config.js projects array lets you run one project with node and another with jsdom without a global default. Use --watch locally (it reruns only changed files) and --ci in pipelines (which forces a single pass and non-interactive output). Jest's snapshot and mock APIs are available globally by default, which is convenient but can lead to tests that are hard to trace — some teams disable globals and require explicit imports for clarity. If your suite grows slow, consider migrating the slowest files to Vitest, which shares Jest's API but runs through esbuild for dramatically faster transforms.
Example
// jest.config.js (CommonJS)
module.exports = {
testEnvironment: "node",
collectCoverageFrom: ["src/**/*.js"],
coverageThreshold: { global: { branches: 80 } },
};
// src/stringUtils.test.js
const { capitalize } = require("./stringUtils");
describe("capitalize", () => {
test("uppercases the first letter", () => {
expect(capitalize("hello")).toBe("Hello");
});
test("handles empty strings", () => {
expect(capitalize("")).toBe("");
});
test("throws on non-string input", () => {
expect(() => capitalize(42)).toThrow(TypeError);
});
});
The config sets the Node environment and a coverage threshold. The test file uses Jest's globals (describe/test/expect) which are available without imports when globals is enabled.
Try it
- Code Diff
Compare expected and actual values from Jest failure output.
- JSON Formatter
Read Jest's JSON reporter output for CI dashboards.
Common mistakes
The mistake
Using toBe for objects and arrays
The fix
toBe checks reference identity. Use toEqual (or toStrictEqual) for deep equality of objects and arrays.
The mistake
Forgetting to await asynchronous assertions
The fix
Return or await the promise inside test(). Jest waits for resolved promises; an unawaited rejection becomes an unhandled error.
Practice Jest Basics
36 exercises
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.