Jest测试教程之一:介绍


在软件开发的过程中,测试的重要性就不用多说了。下面介绍JavaScript的测试框架:Jest。

Jest
Jest

Jest介绍

Jest是著名的JavaScript测试框架之一(还有MochaJasmine )。它的功能强大,简单易用,性能卓越,很多大厂都选择Jest这个框架。

安装及设置

运行如下命令创建一个测试项目:

bash
mkdir jestdemo
cd jestdemo
npm init -y
npm install jest -D

添加基本测试用例

添加calc.js

JavaScript
function add(a, b){     
    return a + b;       
}                       
                        
function minus(a, b) {  
    return a - b;       
}                       
                        
module.exports = {      
    add, minus          
}

添加calc.test.js

JavaScript
const calc = require('./calc');
const { add , minus }  = calc

test('Testing function add',() => {
    expect(add(3, 5)).toBe(8)
})

test('Testing function minus',() => {
    expect(minus(8, 5)).toBe(3)
})

更新package.json

json
{
  "name": "jestdemo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "jest"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "jest": "^27.4.7"
  }
}

运行测试

运行如下命令:

bash
npm run test

可以看到如下输出:

bash
> [email protected] test
> jest

 PASS  ./calc.test.js
  √ Testing function add (4 ms)
  √ Testing function minus

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        0.692 s
Ran all test suites.

测试覆盖率报告

如果把package.json中的设置改为:

json
"scripts": {
  "test": "jest",
  "coverage": "jest --coverage"
},

运行命令:

bash
npm run coverage

就可以看到测试报告中的测试覆盖率信息:

bash
----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |
 calc.js  |     100 |      100 |     100 |     100 |
----------|---------|----------|---------|---------|-------------------

同时还会在coverage文件夹中创建测试报告,比如html版本的报告:

Jest
Jest

调试技巧:只运行单一测试

如果有很多测试,一旦某个测试无法通过,想要集中精力排错的话,可以使用test.only来临时只运行单一测试:

JavaScript
test.only('这是唯一将被运行的测试', () => {
  expect(true).toBe(false);
});

在项目中使用ES6语法

目前使用的是Common JS的require,如果想要使用ES6的语法,就需要使用Babel进行转换才可以。

首先安装依赖库:

bash
npm i @babel/core @babel/preset-env -D

增加.babelrc:

json
{
    "presets":[
        [
            "@babel/preset-env",{
                "targets": {
                    "node": "current"
                }
            }
        ]
    ]
}

然后就可以使用ES6语法了:

JavaScript
import { add, minus} from './calc';

文章作者: 逻思
版权声明: 本博客所有文章除特別声明外,均采用 CC BY-NC-ND 4.0 许可协议。转载请注明来源 逻思 !