快速入门
本页面由 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: {},
};