Jest是Facebook一套开源的 JavaScript 测试框架,它自动集成了断言、JSDom、覆盖率报告等测试工具。
他适用但不局限于使用以下技术的项目:Babel, TypeScript, Node, React, Angular, Vue
官网地址:https://jestjs.io/en/
使用 yarn 安装 Jest︰
yarn add --dev jest
或 npm:
npm install --save-dev jest
注:Jest的文档统一使用yarn命令,不过使用npm也是可行的。 你可以在yarn的说明文档里看到yarn与npm之间的对比。
jest
├── request.js
├── request.test.js
└── package.json
package
{
"name": "jest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"jest": "^26.6.3"
}
}
function sum(a, b) {
return a + b;
}
module.exports = sum;
const sum = require('./request.js');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
将下面的配置部分添加到你的 package.json 里面:
{
"scripts": {
"test": "jest"
}
}
PASS ./request.test.js
✓ adds 1 + 2 to equal 3 (5 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.845 s
Ran all test suites.
✨ Done in 3.29s.
全局安装Jest命令行:
yarn global add jest
或者
npm install jest --global
最后,运行 jest --init ,Jest将打印下面这个消息:
LiuJun-MacBook-Pro:jest liujun$ jest --init
The following questions will help Jest to create a suitable configuration for your project
✔ Would you like to use Typescript for the configuration file? … no
✔ Choose the test environment that will be used for testing › node
✔ Do you want Jest to add coverage reports? … yes
✔ Which provider should be used to instrument code for coverage? › v8
✔ Automatically clear mock calls and instances between every test? … yes
Configuration file created at /Users/liujun/Documents/huayun/test/jest/jest.config.js
生成一个基础配置文件 jest.config.js
/*
* For a detailed explanation regarding each configuration property, visit:
* https://jestjs.io/docs/en/configuration.html
*/
module.exports = {
// Automatically clear mock calls and instances between every test
clearMocks: true,
// The directory where Jest should output its coverage files
coverageDirectory: "coverage",
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "/node_modules/"
// ],
// Indicates which provider should be used to instrument code for coverage
coverageProvider: "v8",
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "json",
// "jsx",
// "ts",
// "tsx",
// "node"
// ],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// A list of paths to directories that Jest should use to search for files in
// roots: [
// ""
// ],
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
testEnvironment: "node", // jest-environment-jsdom or node
// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ]
};
jest.config.js 配置说明:https://jestjs.io/docs/zh-Hans/configuration
https://www.jianshu.com/p/2f00475ade2a
例如,将覆盖率输出的路劲修改为:coverage-test
{
coverageDirectory: "coverage-test",
}
然后添加一个生成覆盖率的脚本 test2
"scripts": {
"test": "jest",
"test2": "jest --coverage"
},
最后执行脚本:yarn test2, 控制台打印如下,并且跟目录会生成 coverage-test 文件夹
LiuJun-MacBook-Pro:jest liujun$ yarn test2
yarn run v1.13.0
$ jest --coverage
PASS ./request.test.js
✓ adds 1 + 2 to equal 3 (3 ms)
(node:59600) ExperimentalWarning: The fs.promises API is experimental
------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
------------|---------|----------|---------|---------|-------------------
All files | 87.5 | 50 | 100 | 87.5 |
request.js | 87.5 | 50 | 100 | 87.5 | 7
------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.824 s
Ran all test suites.
✨ Done in 3.62s.
如果项目使用ES6的语法,要给Jest配置Babel
// ES6
export const sum = (a, b) => {
return a + b;
}
// function sum(a, b) {
// return a + b;
// }
// module.exports = sum;
// ES6
import { sum } from './request.js'
// const sum = require('./request.js');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
LiuJun-MacBook-Pro:jest liujun$ yarn test2
yarn run v1.13.0
$ jest --coverage
FAIL ./request.test.js
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
/Users/liujun/Documents/huayun/test/jest/request.test.js:1
({"Object." :function(module,exports,require,__dirname,__filename,global,jest){import { sum } from './request.js'; // const sum = require('./request.js');
^
SyntaxError: Unexpected token {
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
如果需要使用 Babel,可以通过 yarn来安装所需的依赖。
yarn add --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'}}]],
};
Babel的配置取决于具体的项目使用场景 ,可以查阅 Babel官方文档来获取更多详细的信息。
LiuJun-MacBook-Pro:jest liujun$ yarn test2
yarn run v1.13.0
$ jest --coverage
PASS ./request.test.js
✓ adds 1 + 2 to equal 3 (7 ms)
(node:60762) ExperimentalWarning: The fs.promises API is experimental
------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
------------|---------|----------|---------|---------|-------------------
All files | 87.5 | 50 | 100 | 87.5 |
request.js | 87.5 | 50 | 100 | 87.5 | 3
------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 3.903 s
Ran all test suites.