Jest单元测试(一)

Jest 简介

Jest是Facebook一套开源的 JavaScript 测试框架,它自动集成了断言、JSDom、覆盖率报告等测试工具。
他适用但不局限于使用以下技术的项目:Babel, TypeScript, Node, React, Angular, Vue

官网地址:https://jestjs.io/en/

Jest 安装

使用 yarn 安装 Jest︰

yarn add --dev jest

或 npm:

npm install --save-dev jest

注:Jest的文档统一使用yarn命令,不过使用npm也是可行的。 你可以在yarn的说明文档里看到yarn与npm之间的对比。

Jest 的基本使用

  1. 新建项目
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"
  }
}
  1. 编写 request.js 文件
function sum(a, b) {
   
    return a + b;
  }
module.exports = sum;
  1. 编写测试 request.test.js 文件
const sum = require('./request.js');

test('adds 1 + 2 to equal 3', () => {
   
    expect(sum(1, 2)).toBe(3);
});

将下面的配置部分添加到你的 package.json 里面:

{
   
  "scripts": {
   
    "test": "jest"
  }
}
  1. 执行测试用例
    最后,运行 yarn test 或 npm run 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 配置文件

全局安装Jest命令行:

yarn global add jest

或者

npm install jest --global

最后,运行 jest --init ,Jest将打印下面这个消息:


LiuJun-MacBook-Pro:jest liujun$ jest --init

The following questions will he
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值