Jest 基础使用

Jest 基础使用

Jest 的安装与运行

Jest 可以通过 npm 进行开发安装:

# 指定安装 jest v23.6,不添加 @23.6.0 会安装最新版本
$ npm install --save-dev jest@23.6.0

注意这里使用了 --save-dev,指的是只有在开发环境下才会下载依赖包,package.jsondevDependencies 也会想对更新:

{
  // 省略其他
  "devDependencies": {
    "jest": "^23.6.0"
  }
}

一旦依赖包安装成功,就可以使用 npx jest 去运行测试文件。

没有测试文件的情况下就会报错。

直接使用 npm 运行文件 Jest 需要在 package.json 中进行配置:

{
  // 省略其他
  "scripts": {
    "test": "jest"
  }
}

编写第一个测试文件

Jest 认知的文件格式为:文件名.test.js,如:helloWorld.test.js:

const greeting = () => 'hello world';

describe('greeting()', () => {
  it('greeting', () => {
    expect(greeting()).toBe('hello world');
  });
});

其中:

  • describe() 声明了这是一个测试凹状,是一组测试
  • it() 声明了一个测试
  • assertion 创建了一个断言
  • toBe() 则是判断返回值是否与断言相等

运行结果:

$ npm test
...
 PASS  ./greeting.test.js
  greeting()
    ✓ greeting (3ms)

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

自动运行测试 及 测试覆盖率

运行测试可以用 --watchAll 作为旗帜:

# 加上关键字全局搜索
$ npx jest --watchAll

这时候,npm 就会监视所有文件的变化,包括实现的文件和测试文件后,重新运行测试。

开启测试覆盖率可以用 --coverage 旗帜,如:

$ npm run test -- --coverage --coverageReporters=text

 PASS  ./index.test.js
  greeting()
    ✓ returns "greeting" for greeting (3ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |       75 |       50 |      100 |    66.67 |                   |
 index.js |       75 |       50 |      100 |    66.67 |                 3 |
----------|----------|----------|----------|----------|-------------------|

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

运行多个测试

只需要在 describe() 作用域中增加多个 it() 声明即可。

const greeting = () => 'hello world';

describe('greeting()', () => {
  it('greeting', () => {
    expect(greeting()).toBe('hello world');
  });
});
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值