Skip to main content
Version: 29.7

入门

使用你最喜欢的包管理器安装 Jest:

¥Install Jest using your favorite package manager:

npm install --save-dev jest

让我们开始为一个将两个数字相加的假设函数编写一个测试。首先,创建一个 sum.js 文件:

¥Let's get started by writing a test for a hypothetical function that adds two numbers. First, create a sum.js file:

function sum(a, b) {
return a + b;
}
module.exports = sum;

然后,创建一个名为 sum.test.js 的文件。这将包含我们的实际测试:

¥Then, create a file named sum.test.js. This will contain our actual test:

const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});

将以下部分添加到你的 package.json 中:

¥Add the following section to your package.json:

{
"scripts": {
"test": "jest"
}
}

最后,运行 yarn testnpm test,Jest 将打印以下消息:

¥Finally, run yarn test or npm test and Jest will print this message:

PASS  ./sum.test.js
✓ adds 1 + 2 to equal 3 (5ms)

你刚刚使用 Jest 成功编写了第一个测试!

¥You just successfully wrote your first test using Jest!

该测试使用 expecttoBe 来测试两个值是否完全相同。要了解 Jest 可以测试的其他内容,请参阅 使用匹配器

¥This test used expect and toBe to test that two values were exactly identical. To learn about the other things that Jest can test, see Using Matchers.

从命令行运行

¥Running from command line

你可以直接从 CLI 运行 Jest(如果它在 PATH 中全局可用,例如 yarn global add jestnpm install jest --global),并具有各种有用的选项。

¥You can run Jest directly from the CLI (if it's globally available in your PATH, e.g. by yarn global add jest or npm install jest --global) with a variety of useful options.

以下是如何在匹配 my-test 的文件上运行 Jest,使用 config.json 作为配置文件并在运行后显示原生操作系统通知:

¥Here's how to run Jest on files matching my-test, using config.json as a configuration file and display a native OS notification after the run:

jest my-test --notify --config=config.json

如果你想了解有关通过命令行运行 jest 的更多信息,请查看 Jest CLI 选项 页面。

¥If you'd like to learn more about running jest through the command line, take a look at the Jest CLI Options page.

附加配置

¥Additional Configuration

生成基本配置文件

¥Generate a basic configuration file

根据你的项目,Jest 会问你几个问题,并创建一个基本配置文件,其中包含每个选项的简短描述:

¥Based on your project, Jest will ask you a few questions and will create a basic configuration file with a short description for each option:

npm init jest@latest

使用 Babel

¥Using Babel

要使用 Babel,请安装所需的依赖:

¥To use Babel, install required dependencies:

npm install --save-dev babel-jest @babel/core @babel/preset-env

通过在项目的根目录中创建 babel.config.js 文件,将 Babel 配置为针对当前版本的 Node:

¥Configure Babel to target your current version of Node by creating a babel.config.js file in the root of your project:

babel.config.js
module.exports = {
presets: [['@babel/preset-env', {targets: {node: 'current'}}]],
};

Babel 的理想配置取决于你的项目。详细信息请参见 Babel 的文档

¥The ideal configuration for Babel will depend on your project. See Babel's docs for more details.

Making your Babel config jest-aware

如果未设置为其他值,Jest 会将 process.env.NODE_ENV 设置为 'test'。你可以在配置中使用它来有条件地仅设置 Jest 所需的编译,例如

¥Jest will set process.env.NODE_ENV to 'test' if it's not set to something else. You can use that in your configuration to conditionally setup only the compilation needed for Jest, e.g.

babel.config.js
module.exports = api => {
const isTest = api.env('test');
// You can use isTest to determine what presets and plugins to use.

return {
// ...
};
};
注意

安装 Jest 时会自动安装 babel-jest,如果项目中存在 babel 配置,babel-jest 会自动转换文件。为了避免这种行为,你可以显式重置 transform 配置选项:

¥babel-jest is automatically installed when installing Jest and will automatically transform files if a babel configuration exists in your project. To avoid this behavior, you can explicitly reset the transform configuration option:

jest.config.js
module.exports = {
transform: {},
};

使用 Webpack

¥Using webpack

Jest 可用于使用 webpack 管理资源、样式和编译的项目。与其他工具相比,webpack 确实带来了一些独特的挑战。请参阅 Webpack 指南 开始。

¥Jest can be used in projects that use webpack to manage assets, styles, and compilation. webpack does offer some unique challenges over other tools. Refer to the webpack guide to get started.

使用 Vite

¥Using Vite

Jest 可用于使用 vite 通过原生 ESM 提供源代码的项目,以提供一些前端工具,vite 是一个有态度的工具,并且确实提供了一些开箱即用的工作流程。由于 vite 的 插件系统 工作方式,vite 不完全支持 Jest,但是有一些使用 vite-jest 进行一流 jest 集成的工作示例,因为这不完全支持,你不妨阅读 vite-jest 的限制。请参阅 Vite 指南 开始。

¥Jest can be used in projects that use vite to serve source code over native ESM to provide some frontend tooling, vite is an opinionated tool and does offer some out-of-the box workflows. Jest is not fully supported by vite due to how the plugin system from vite works, but there are some working examples for first-class jest integration using vite-jest, since this is not fully supported, you might as well read the limitation of the vite-jest. Refer to the vite guide to get started.

使用 Parcel

¥Using Parcel

Jest 可以用在使用 parcel-bundler 的项目中,类似于 webpack 来管理资源、样式和编译。Parcel 需要零配置。参考官方 文档 入门。

¥Jest can be used in projects that use parcel-bundler to manage assets, styles, and compilation similar to webpack. Parcel requires zero configuration. Refer to the official docs to get started.

使用 TypeScript

¥Using TypeScript

通过 babel

¥Via babel

Jest 通过 Babel 支持 TypeScript。首先,确保你遵循了上面 使用 Babel 的说明。接下来,安装 @babel/preset-typescript

¥Jest supports TypeScript, via Babel. First, make sure you followed the instructions on using Babel above. Next, install the @babel/preset-typescript:

npm install --save-dev @babel/preset-typescript

然后将 @babel/preset-typescript 添加到 babel.config.js 中的预设列表中。

¥Then add @babel/preset-typescript to the list of presets in your babel.config.js.

babel.config.js
module.exports = {
presets: [
['@babel/preset-env', {targets: {node: 'current'}}],
'@babel/preset-typescript',
],
};

然而,在 Babel 中使用 TypeScript 存在一些 注意事项 问题。因为 Babel 中的 TypeScript 支持纯粹是转译,所以 Jest 不会在运行时对你的测试进行类型检查。如果你愿意,可以改用 ts-jest,或者单独运行 TypeScript 编译器 tsc(或作为构建过程的一部分)。

¥However, there are some caveats to using TypeScript with Babel. Because TypeScript support in Babel is purely transpilation, Jest will not type-check your tests as they are run. If you want that, you can use ts-jest instead, or just run the TypeScript compiler tsc separately (or as part of your build process).

通过 ts-jest

¥Via ts-jest

ts-jest 是一个 TypeScript 预处理器,支持 Jest 的源映射,让你可以使用 Jest 测试用 TypeScript 编写的项目。

¥ts-jest is a TypeScript preprocessor with source map support for Jest that lets you use Jest to test projects written in TypeScript.

npm install --save-dev ts-jest

为了让 Jest 使用 ts-jest 转译 TypeScript,你可能还需要创建一个 配置 文件。

¥In order for Jest to transpile TypeScript with ts-jest, you may also need to create a configuration file.

类型定义

¥Type definitions

有两种方法可以为用 TypeScript 编写的测试文件输入 Jest 全局 API

¥There are two ways to have Jest global APIs typed for test files written in TypeScript.

你可以使用 Jest 附带的类型定义,并且每次更新 Jest 时都会更新。安装 @jest/globals 包:

¥You can use type definitions which ships with Jest and will update each time you update Jest. Install the @jest/globals package:

npm install --save-dev @jest/globals

并从中导入 API:

¥And import the APIs from it:

sum.test.ts
import {describe, expect, test} from '@jest/globals';
import {sum} from './sum';

describe('sum module', () => {
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
});
提示

请参阅 describe.each/test.eachmock functions 的附加使用文档。

¥See the additional usage documentation of describe.each/test.each and mock functions.

或者你可以选择安装 @types/jest 软件包。它为 Jest 全局变量提供类型,无需导入它们。

¥Or you may choose to install the @types/jest package. It provides types for Jest globals without a need to import them.

npm install --save-dev @types/jest
信息

@types/jest 是在 DefinitelyTyped 维护的第三方库,因此可能尚未涵盖最新的 Jest 功能或版本。尝试尽可能匹配 Jest 和 @types/jest 的版本。例如,如果你使用 Jest 27.4.0,那么安装 27.4.x@types/jest 是理想的选择。

¥@types/jest is a third party library maintained at DefinitelyTyped, hence the latest Jest features or versions may not be covered yet. Try to match versions of Jest and @types/jest as closely as possible. For example, if you are using Jest 27.4.0 then installing 27.4.x of @types/jest is ideal.

使用 ESLint

¥Using ESLint

Jest 可以与 ESLint 一起使用,无需任何进一步配置,只要你在测试文件中使用它们之前从 @jest/globals 导入 Jest 全局助手describeit 等)即可。这是避免 ESLint 出现 no-undef 错误所必需的,因为 ESLint 不知道 Jest 全局变量。

¥Jest can be used with ESLint without any further configuration as long as you import the Jest global helpers (describe, it, etc.) from @jest/globals before using them in your test file. This is necessary to avoid no-undef errors from ESLint, which doesn't know about the Jest globals.

如果你想避免这些导入,你可以通过添加 jest 环境来配置 ESLint 环境 以支持这些全局变量:

¥If you'd like to avoid these imports, you can configure your ESLint environment to support these globals by adding the jest environment:

{
"overrides": [
{
"files": ["tests/**/*"],
"env": {
"jest": true
}
}
]
}

或者使用 eslint-plugin-jest,也有类似的效果:

¥Or use eslint-plugin-jest, which has a similar effect:

{
"overrides": [
{
"files": ["tests/**/*"],
"plugins": ["jest"],
"env": {
"jest/globals": true
}
}
]
}