快速开始
使用你最喜欢的包管理器安装Jest:
- npm
- Yarn
- pnpm
- Bun
npm install --save-dev jest
yarn add --dev jest
pnpm add --save-dev jest
bun add --dev jest
举个例子,我们先写一个两数相加的函数。 First, create a sum.js file:
function sum(a, b) {
return a + b;
}
module.exports = sum;
Then, create a file named sum.test.js. 此文件中将包含我们的实际测试︰
const sum = require('./sum');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
Add the following section to your package.json:
{
"scripts": {
"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)
You just successfully wrote your first test using 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.
在命令行中运行
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.
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
If you'd like to learn more about running jest through the command line, take a look at the Jest CLI Options page.
更多配置
生成基础配置文件
基于您的项目,Jest将向您提出几个问题,并将创建一个基本的配置文件,每个选项都有一个简短的说明:
- npm
- Yarn
- pnpm
- Bun
npm init jest@latest
yarn create jest
pnpm create jest
bunx create-jest
使用 Babel
To use Babel, install required dependencies:
- 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
Configure Babel to target your current version of Node by creating a babel.config.js file in the root of your project:
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.
Making your Babel config jest-aware
Jest will set process.env.NODE_ENV to 'test' if it's not set to something else.
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 can be used in projects that use webpack to manage assets, styles, and compilation. webpack 与其他工具相比多了一些独特的挑战。 Refer to the webpack guide to get started.
使用 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
Jest can be used in projects that use parcel-bundler to manage assets, styles, and compilation similar to webpack. Refer to the official docs to get started.
使用 TypeScript
Via babel
Jest可以通过Babel支持TypeScript。 First, make sure you followed the instructions on using Babel above. Next, install the @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
Then add @babel/preset-typescript to the list of presets in your babel.config.js.
module.exports = {
presets: [
['@babel/preset-env', {targets: {node: 'current'}}],
'@babel/preset-typescript',
],
};
However, there are some caveats to using TypeScript with Babel. 因为Babel对Typescrip的支持是纯编译形式(无类型校验),因此Jest在运行测试时不会对它们进行类型检查。 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).
Via ts-jest
ts-jest is a TypeScript preprocessor with source map support for Jest that lets you use Jest to test projects written in 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
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. Install the @jest/globals package:
- 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);
});
});
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
- 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 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
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
}
}
]
}