跳转至主内容
版本:下一个

快速开始

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

npm install --save-dev jest

举个例子,我们先写一个两数相加的函数。 首先,创建 sum.js 文件︰

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

然后,创建名为 sum.test.js 的文件。 此文件中将包含我们的实际测试︰

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

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

随后,将下列配置内容添加到您的 package.json

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

最后,运行 yarn testnpm run test ,Jest将打印下面这个消息:

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

您刚刚完成了您的首个 Jest 测试!

此测试使用 expecttoBe 来测试两值是否一致。 要了解 Jest 能进行的更多测试,请参阅使用匹配器章节。

在命令行中运行

你可以通过命令行直接运行Jest(前提是jest已经处于你的环境变量 PATH中,例如通过 yarn global add jestnpm install jest --global安装的Jest) ,并为其指定各种有用的配置项。

这里演示了如何对能匹配到 my-test 的文件运行 Jest、使用config.json 作为一个配置文件、并在运行完成后显示一个原生的操作系统通知。

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

如果你愿意了解更多关于通过命令行运行 jest 的内容,请继续阅读 Jest CLI 选项 页面。

更多配置

生成基础配置文件

基于您的项目,Jest将向您提出几个问题,并将创建一个基本的配置文件,每个选项都有一个简短的说明:

npm init jest@latest

使用 Babel

如果需要使用 Babel,安装所需的依赖。

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

可以在工程的根目录下创建一个babel.config.js文件用于配置与你当前Node版本兼容的Babel:

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

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

Jest与Babel的协同

process.env.NODE_ENV 未设置,Jest将把它设置为 'test' 。你可以用 if语句设置Jest执行的编译配置。例如:

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

return {
// ...
};
};
备注

babel-jest is automatically installed when installing Jest and will automatically transform files if a babel configuration exists in your project. 如果要避免这个行为,你可以显式的重置 transform 配置项:

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

使用 webpack

Jest 可以用于使用 webpack 来管理资源、 样式和编译的项目中。 webpack 与其他工具相比多了一些独特的挑战。 参考 webpack 指南 来开始起步。

使用 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

Parcel是一个类似于Webpack的零配置管理资源及样式的构建工具。Jest可以在Parcel构建的项目中使用。可以去Parcel官网 尝试一下。 请查看Parcel的 官方文档 进行操作。

使用 TypeScript

通过 babel实现

Jest可以通过Babel支持TypeScript。 首先,在项目中正确的使用Babel。 接着,安装 @babel/preset-typescript

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

你需要添加@babel/preset-typescript的预设到babel.config.js.

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

不过,在配合使用TypeScript与Babel时,仍然有一些 注意事项 。 因为Babel对Typescrip的支持是纯编译形式(无类型校验),因此Jest在运行测试时不会对它们进行类型检查。 如果需要类型校验,可以改用ts-jest,也可以单独运行TypeScript编译器 tsc (或作为构建过程的一部分)。

通过 ts-jest实现

ts-jest 是一个支持 sourcemap 的 TypeScript 预处理器,让你使用 TypeScript 编写 Jest 测试项目

npm install --save-dev ts-jest

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

类型定义

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

You can use type definitions which ships with Jest and will update each time you update Jest. 安装 @jest/globals 包:

npm install --save-dev @jest/globals

然后从中导入API:

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);
});
});
提示

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

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 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.

Using ESLint

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.

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
}
}
]
}

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

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