认识下 Jest 单元测试

908 阅读2分钟

这是我参与11月更文挑战的第27天,活动详情查看:2021最后一次更文挑战

安装

# 使用 yarn 安装Jest
yarn add  jest --dev 
​
# 使用npm 安装Jest 
npm i jest --save-dev

安装后会在package.json增加了Jest的配置。Jest的配置可以通过package.json或是jest.config.js文件来配置。其还支持其他格式:--config <path/to/file.js|cjs|mjs|json>

配置

主要是通过配置文件jest-config.json进行单元测试,所以可以在package.json中的script 中增加命令。

"script": {
  # 单测命令
"test""jest --config ./jest-config.json --`detectOpenHandles` `--env=node`",
# 覆盖率
"test:cov": "jest --config ./jest-config.json  --coverage" 
}

配置项说明

--detectOpenHandles 参数是为了当句柄未正常关闭,显式报错给用户;

--env=node 指明测试环境是 nodejs,默认是浏览器。

--coverage 测试覆盖率信息并生成报告

其中单元测试的覆盖率通过使用命令:jest --coverage

jest-html-reporter

jest-html-reporter是基于 Jest 生成 html 报表的工具。

yarn add jest-html-reporter --dev

原 Jest框架也自带生成 html 报表的测试报告。也是支持使用其他的测试报告格式,如使用 jest-html-reporter 生成测试报告. jest-html-reporter 基于 Jest 生成 html 报表的工具。

jest-config.json

{
  "moduleFileExtensions": ["js", "json", "ts"],
  "rootDir": "./",
  "testRegex": ".spec.ts$",
  "transform": {
    "^.+\.(t|j)s$": "ts-jest"
  },
  "collectCoverageFrom": ["**/*.(t|j)s"],
  "moduleDirectories": [".", "src", "../src", "./node_modules"],
  "reporters": [
    "default",
    [
      "<rootDir>/node_modules/jest-html-reporter",
      {
        "pageTitle": "Unit Tests",
        "outputPath": "./coverage/unit-test/index.html",
        "includeFailureMsg": true
      }
    ]
  ],
  "coverageReporters": ["clover", "json", "lcov", "text"],
  "coverageDirectory": "./coverage/unit-test",
  "coveragePathIgnorePatterns": [".module.ts$", ".spec.ts$"],
  "testEnvironment": "node"
}
  • testRegex 用于指定测试文件,支持正则表达方式或者具体的文件

  • coverageReporters

    • 覆盖率报告格式:["clover", "json", "lcov", "text"]
  • collectCoverageFrom

    • 是收集符合 Glob 模式匹配的文件的测试覆盖率,此属性至于在 collectCoverage = true 或者 命令行中带有 --coverage 参数时生效

      • collectCoverage = true ,只会收集测试过程中用到的非测试文件的测试覆盖率
      • collectCoverage = true , collectCoverageForm = [ ... ],只会收集 collectCoverageFrom 指定的非测试文件的测试覆盖率,而且不管该文件有没有在测试中被用到,都会收集,但不过覆盖率为0
      • 设置 collectCoverageForm = [ ... ] ,可让你知道你的代码哪些未被覆盖到。
  • collectCoverage

    • 默认值是 false 。指是否收集测试时的覆盖率信息。 由于要带上覆盖率搜集语句重新访问所有执行过的文件,可能导致测试速度减慢

参考资料