Jest

愉快的 JavaScript 测试。(Delightful JavaScript Testing.)

Github stars Tracking Chart

愉快的 JavaScript 测试

  • 开发者就绪。一个全面的 JavaScript 测试解决方案。对于大多数 JavaScript 项目来说,开箱即用。
  • 即时反馈。快速、交互式的观察模式,只运行与更改文件相关的测试文件。
  • 快照测试。捕捉大型对象的快照,以简化测试并分析它们如何随时间变化。

jestjs.io 上查看更多。

入门

使用 yarn 安装 Jest:

yarn add --dev jest

或者 npm

npm install --save-dev jest

注意:Jest 文档使用 yarn 命令,但 npm 也可以使用。你可以在 这里的 yarn 文档 中比较 yarn 和 npm 命令。

让我们先为一个假设的函数写一个测试,将两个数字相加。首先,创建一个 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 run test,Jest 会打印这条信息。

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

你刚刚用 Jest 成功地写了第一个测试!这个测试使用了 expect 和 toBe 来测试两个值完全相同。

这个测试使用 expect 和 toBe 来测试两个值是否完全相同。要了解 Jest 可以测试的其他内容,请看使用匹配器

从命令行运行

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

下面是如何在与my-test匹配的文件上运行 Jest,使用 config.json 作为配置文件,并在运行后显示本地操作系统通知。

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

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

其他配置

生成一个基本配置文件

根据你的项目,Jest 会问你几个问题,并为每个选项创建一个带有简短描述的基本配置文件。

jest --init

使用 Babel

要使用 Babel,请通过 yarn 安装所需的依赖项。

yarn add --dev babel-jest @babel/core @babel/preset-env

如果您还没有为您的项目配置 babel,您可以通过在项目根目录下创建一个 babel.config.js 文件来使用 Babel 来锁定您当前版本的 Node。

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

Babel 的理想配置取决于您的项目。更多细节请参考 Babel 的文档

让您的 Babel 配置具有jest-aware功能

如果没有设置为其他,Jest 会将 process.env.NODE_ENV 设置为 'test'。您可以在您的配置中使用这一点来有条件地设置 Jest 所需的编译,例如:

// babel.config.js
module.exports = api => {
  const isTest = api.env('test');
  // 你可以使用 isTest 来决定使用什么预设和插件。
  return {
    // ...
  };
};

注意:babel-jest 是在安装 Jest 时自动安装的,如果您的项目中存在 babel 配置,它将自动转换文件。为了避免这种行为,您可以明确地重置转换配置选项。

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

使用 webpack

Jest 可以用于使用 webpack 管理资产、样式和编译的项目中,与其他工具相比,webpack 确实提供了一些独特的挑战。请参考 webpack 指南来入门。

使用 parcel

Jest 可以用于使用 parcel-bundler 管理资产、样式和编译的项目中,类似于 webpack。Parcel 不需要任何配置。

使用 TypeScript

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

yarn add --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',
  ],
};

注意,在 Babel 中使用 TypeScript 有一些注意事项。因为 Babel 中对 TypeScript 的支持是转置的,所以 Jest 不会在您的测试运行时对它们进行类型检查。如果您想要这样,您可以使用 ts-jest

文档

Jest 官方网站上了解更多关于使用 Jest 的信息!

徽章

向世界展示您正在使用 Jest

[![tested with jest](https://img.shields.io/badge/tested_with-jest-<span class="pl-c1">99424f</span>.svg)](https://github.com/facebook/jest)
[![jest](https://jestjs.io/img/jest-badge.svg)](https://github.com/facebook/jest)

许可证

Jest 是 MIT 授权的


(The first version translated by vz on 2020.08.30)

Overview

Name With Ownerjestjs/jest
Primary LanguageTypeScript
Program languageJavaScript (Language Count: 6)
PlatformLinux, Mac, Windows
License:MIT License
Release Count294
Last Release Namev30.0.0-alpha.4 (Posted on 2024-05-12 23:43:11)
First Release Namev0.1.0 (Posted on 2014-05-14 10:32:17)
Created At2013-12-10 00:18:04
Pushed At2024-05-13 15:43:03
Last Commit At
Stargazers Count43.6k
Watchers Count559
Fork Count6.4k
Commits Count7.2k
Has Issues Enabled
Issues Count7765
Issue Open Count300
Pull Requests Count5480
Pull Requests Open Count47
Pull Requests Close Count1673
Has Wiki Enabled
Is Archived
Is Fork
Is Locked
Is Mirror
Is Private

??‍? Developer Ready: A comprehensive JavaScript testing solution. Works out of the box for most JavaScript projects.

?? Instant Feedback: Fast, interactive watch mode only runs test files related to changed files.

? Snapshot Testing: Capture snapshots of large objects to simplify testing and to analyze how they change over time.

Table of Contents

Getting Started

Install Jest using yarn:

yarn add --dev jest

Or npm:

npm install --save-dev jest

Note: Jest documentation uses yarn commands, but npm will also work. You can compare yarn and npm commands in the yarn docs, here.

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;

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

Add the following section to your package.json:

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

Finally, run yarn test or npm run 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.

Running from command line

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.

Additional Configuration

Generate a basic configuration file

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:

jest --init

Using Babel

To use Babel, install required dependencies via yarn:

yarn add --dev babel-jest @babel/core @babel/preset-env

If you do not already have babel configured for your project, you can use 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: ,
};

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

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 {
    // ...
  };
};

Note: 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: {},
};

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

Using TypeScript

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

yarn add --dev @babel/preset-typescript

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',
  ],
};

Note, there are some caveats to using TypeScript with Babel. Because TypeScript support in Babel is transpilation, Jest will not type-check your tests as they are run. If you want that, you can use ts-jest.

Documentation

Learn more about using Jest on the official site!

Badge

Show the world you're using Jest tested with jest jest

[![tested with jest](https://img.shields.io/badge/tested_with-jest-99424f.svg)](https://github.com/facebook/jest) [![jest](https://jestjs.io/img/jest-badge.svg)](https://github.com/facebook/jest)

Contributing

Development of Jest happens in the open on GitHub, and we are grateful to the community for contributing bugfixes and improvements. Read below to learn how you can take part in improving Jest.

Code of Conduct

Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please read the full text so that you can understand what actions will and will not be tolerated.

Contributing Guide

Read our contributing guide to learn about our development process, how to propose bugfixes and improvements, and how to build and test your changes to Jest.

Good First Issues

To help you get your feet wet and get you familiar with our contribution process, we have a list of good first issues that contain bugs which have a relatively limited scope. This is a great place to get started.

Credits

This project exists thanks to all the people who contribute.

Backers

Thank you to all our backers! ?

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website.

License

Jest is MIT licensed.

To the top