Jest 基础使用

Jest 基础使用

Jest 的安装与运行

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

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

注意这里使用了 --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');
  });
});

猜你喜欢

转载自blog.csdn.net/weixin_42938619/article/details/121011940