快速入门
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
使用你喜欢的包管理器安装 Jest:
- npm
- Yarn
- pnpm
- Bun
npm install --save-dev jest
yarn add --dev jest
pnpm add --save-dev jest
bun add --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 test 或 npm test,Jest 将会输出如下信息:
PASS ./sum.test.js
✓ adds 1 + 2 to equal 3 (5ms)
你已成功使用 Jest 编写了第一个测试!
该测试使用了 expect 和 toBe 来验证两个值是否完全相等。要了解 Jest 的其他测试能力,请参阅使用匹配器。
通过命令行运行
如果 Jest 已在全局可用(例如通过 yarn global add jest 或 npm install jest --global 安装到 PATH 中),你可以直接从 CLI 运行 Jest 并搭配多种实用选项。
以下示例展示如何运行匹配 my-test 的测试文件,使用 config.json 作为配置文件,并在运行完成后显示系统原生通知:
jest my-test --notify --config=config.json
如需了解有关通过命令行运行 jest 的更多信息,请查看 Jest 命令行选项 页面。
额外配置
生成基础配置文件
Jest 会根据你的项目提出几个问题,然后创建一个基础配置文件,其中包含每个选项的简要说明:
- npm
- Yarn
- pnpm
- Bun
npm init jest@latest
yarn create jest
pnpm create jest
bunx create-jest
使用 Babel
要使用 Babel,请先安装所需依赖:
- npm
- Yarn
- pnpm
- Bun
npm install --save-dev babel-jest @babel/core @babel/preset-env
yarn add --dev babel-jest @babel/core @babel/preset-env
pnpm add --save-dev babel-jest @babel/core @babel/preset-env
bun add --dev babel-jest @babel/core @babel/preset-env
在项目根目录创建 babel.config.js 文件,将 Babel 配置为针对当前 Node 版本:
module.exports = {
presets: [['@babel/preset-env', {targets: {node: 'current'}}]],
};
Babel 的最佳配置取决于具体项目。更多细节请参阅 Babel 文档。
Making your Babel config jest-aware
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.
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. To avoid this behavior, you can explicitly reset the transform configuration option:
module.exports = {
transform: {},
};
与打包工具配合使用
多数情况下,你无需特殊配置即可与不同打包工具协同工作——除非你使用了生成文件的插件/配置或自定义文件解析规则。
使用 webpack
Jest 可用于使用 webpack 管理资源、样式和编译的项目。webpack 相比其他工具会带来一些独特挑战。请参考 webpack 指南 开始使用。
使用 Vite
由于与 Vite 插件系统 存在兼容性问题,Vite 不支持 Jest。
vite-jest 库提供了 Jest 与 Vite 集成的示例。但请注意,该库不兼容 Vite 2.4.2 之后的版本。
替代方案之一是 Vitest,其 API 与 Jest 兼容。
使用 Parcel
Jest 可用于使用 parcel-bundler 管理资源、样式和编译的项目(与 webpack 类似)。Parcel 无需任何配置。请参阅官方文档开始使用。
使用 TypeScript
通过 babel
Jest 通过 Babel 支持 TypeScript。首先请确保已完成上文 使用 Babel 的配置步骤。接着安装 @babel/preset-typescript:
- npm
- Yarn
- pnpm
- Bun
npm install --save-dev @babel/preset-typescript
yarn add --dev @babel/preset-typescript
pnpm add --save-dev @babel/preset-typescript
bun add --dev @babel/preset-typescript
然后将 @babel/preset-typescript 添加到你的 babel.config.js 的 presets 列表中。
module.exports = {
presets: [
['@babel/preset-env', {targets: {node: 'current'}}],
'@babel/preset-typescript',
],
};
不过,通过 Babel 使用 TypeScript 存在一些注意事项。由于 Babel 对 TypeScript 的支持仅限于代码转译,Jest 在运行测试时不会进行类型检查。如果你需要该功能,可以改用 ts-jest,或者单独运行 TypeScript 编译器 tsc(也可将其作为构建流程的一部分)。
通过 ts-jest
ts-jest 是一个为 Jest 提供的 TypeScript 预处理器,支持源码映射功能,让你能够使用 Jest 测试 TypeScript 项目。
- npm
- Yarn
- pnpm
- Bun
npm install --save-dev ts-jest
yarn add --dev ts-jest
pnpm add --save-dev ts-jest
bun add --dev ts-jest
为了让 Jest 通过 ts-jest 转译 TypeScript,你可能还需要创建配置文件。
类型定义
有两种方式可以为 TypeScript 编写的测试文件添加 Jest 全局 API 的类型定义。
第一种是使用 Jest 自带的类型定义(这些类型会随 Jest 更新而同步更新)。安装 @jest/globals 包:
- npm
- Yarn
- pnpm
- Bun
npm install --save-dev @jest/globals
yarn add --dev @jest/globals
pnpm add --save-dev @jest/globals
bun add --dev @jest/globals
然后从中导入 API:
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.each 和 mock functions 的额外使用文档。
第二种方式是安装 @types/jest 包。这个包提供了 Jest 全局变量的类型定义,无需额外导入。
- npm
- Yarn
- pnpm
- Bun
npm install --save-dev @types/jest
yarn add --dev @types/jest
pnpm add --save-dev @types/jest
bun add --dev @types/jest
@types/jest 是由 DefinitelyTyped 维护的第三方库,因此可能无法及时覆盖 Jest 的最新特性或版本。建议尽量保持 Jest 和 @types/jest 的版本匹配。例如,如果你使用 Jest 27.4.0 版本,那么安装 27.4.x 版本的 @types/jest 是最佳选择。
使用 ESLint
只要在使用 Jest 全局辅助函数(describe、it 等)前从 @jest/globals 导入它们,Jest 就能与 ESLint 直接配合使用,无需额外配置。这样做可以避免 ESLint 因无法识别 Jest 全局变量而抛出 no-undef 错误。
如果希望避免这些导入操作,可以通过配置 ESLint 环境来支持这些全局变量,添加 jest 环境即可:
import {defineConfig} from 'eslint/config';
import globals from 'globals';
export default defineConfig([
{
files: ['**/*.js'],
languageOptions: {
globals: {
...globals.jest,
},
},
rules: {
'no-unused-vars': 'warn',
'no-undef': 'warn',
},
},
]);
或者使用 eslint-plugin-jest 插件,也能达到类似效果:
{
"overrides": [
{
"files": ["tests/**/*"],
"plugins": ["jest"],
"env": {
"jest/globals": true
}
}
]
}