10

使用Jest进行前端单元测试

 2 years ago
source link: https://shiau.xyz/0167b07be208/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

使用Jest进行前端单元测试

2021-03-304 分钟

对于逻辑复杂、迭代频繁的前端项目,进行单元测试很有必要。

这样可以节省大量E2E测试的时间,保证代码的可靠性,量化评估研发团队、测试团队的产出。

常见的前端单元测试框架,有Mocha、Jasmine、Jest。我的选型思路如下:

  • Mocha不自带断言,需要结合其他断言库才可使用。Jasmine、Jest自带断言;
  • Github上,Star数分别是:Mocha 20.4k,Jasmine 15.1k,Jest 34.7k;
  • Jest由Facebook出品。

综上,选择Jest。

2. 覆盖率报告

先说重点:

  • Jest自带HTML格式的覆盖率报告,没有必要再安装jest-html-reporter这种第三方库。
  • 要生成HTML覆盖率报告,需要手动修改Jest配置文件。

先配置一下Jest。如果按照官网的教程,直接执行jest --init会报错。应该执行:

npx jest --init

选择需要覆盖率报告:

image-20210330181059941.png

配置完成后,会生成一个jest.config.js文件。

执行npm test,还是没有覆盖率报告:

image-20210330181831275.png

还得修改jest.config.js文件,将 collectCoverage设置为true,并解除注释:

// Indicates whether the coverage information should be collected while executing the test
collectCoverage: true,

再次执行npm test,控制台就会展示覆盖率情况了:

image-20210330181935226.png

同时,Jest会生成一个coverage目录,其子目录lcov-report内的index.html就是HTML格式的覆盖率报告了:

image-20210330182009207.png

3. 第三方覆盖率报告

如果想要使用jest-html-reporter这个第三方库生成覆盖率报告,也不要按它主页所说的进行配置。直接在package.json新增如下配置最方便:

"jest": {
  "reporters": [
    "default",
    ["./node_modules/jest-html-reporter", {
      "pageTitle": "Test Report"
    }]
  ]
}

jest-html-reporter生成的覆盖率报告如下:

image-20210330175620686.png

对比一下,还是Jest原生的覆盖率报告信息更全、样式更美观。

4. 量化评估产出

看覆盖率报告即可:

  • 覆盖率不够:测试团队需要补充测试用例;
  • 通过率不是100%:研发团队需要修正bug,提高代码质量。
正在检查 Disqus 能否访问...

Powered by  & DisqusJS


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK