Skip to content

Jest 基础

获取开始使用 Jest: 配置, 测试块, matchers, and CLI.

你将学到

  • 如何 安装 and 配置 Jest for JavaScript or TypeScript 项目
  • 编写描述, 测试, and expect 使用 Jest matchers
  • 运行 Jest in watch and CI 模式
  • 理解 Jest's 模块 isolation and 配置 options

概念讲解

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 添加 -D jest (and ts-jest or @swc/jest for TypeScript). Run npx jest --init to generate a jest.配置.js with sensible defaults. Key options include testEnvironment (节点 vs jsdom), transform for TypeScript, and moduleNameMapper to alias @ to src. Add scripts "测试": "jest --watch" and "测试:CI": "jest --CI".

Test Structure

Jest uses 描述 for groups, 测试 (or 它) for cases, and expect(值).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.配置.js 项目 array lets you run one project with 节点 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.

示例代码

              // 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);
  });
});
            

配置设置节点环境 and coverage threshold. 测试 file uses Jest's globals (描述/测试/expect) 哪个是 available 不使用导入当 globals 是启用.

动手试一试

  • Code Diff

    Compare expected and 实际值 从 Jest 失败输出.

  • JSON Formatter

    读取 Jest's JSON reporter 输出 for CI dashboards.

常见错误

错误写法

Using toBe for 对象 and 数组

正确做法

toBe 检查引用 identity. Use toEqual (or toStrictEqual) for deep equality 的对象 and 数组.

错误写法

Forgetting 到等待 asynchronous assertions

正确做法

返回 or 等待 Promise 内部测试(). Jest waits for resolved Promise; unawaited rejection becomes unhandled 错误.

练习 Jest 基础

36 个练习

练习 Jest 基础

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误