将 Sonarqube 的覆盖范围与 istabuljs/nyc 合并

Merge coverage for Sonarqube with istabuljs/nyc

我有一个 typescript 项目,它通过 Jenkins 管道并并行执行所有功能测试(在构建主容器之后)。在管道的末端——我们创建代码覆盖率检查,然后将结果发送到 sonarqube。

这是我的 package.json:

"test": "npm run test:unit && npm run test:component && npm run test:functional",
"test:component": "mocha --reporter mocha-sonarqube-reporter --reporter-options output=tests/coverage/component/test-xcomponent.xml --recursive -r ts-node/register tests/component/*.ts",
"test:functional": "mocha --reporter mocha-sonarqube-reporter --reporter-options output=tests/coverage/functional/test-xfunctional.xml --recursive -r ts-node/register tests/functional/*.ts",
"test:unit": "mocha --reporter mocha-sonarqube-reporter --reporter-options output=tests/coverage/unit/test-xunit.xml --recursive -r ts-node/register tests/unit/*.ts",
"test:unit:nosq": "mocha --recursive -r ts-node/register tests/unit/*.ts",
"lint": "tslint -t verbose --project tsconfig.json -c tslint.json",
"cover": "nyc --report-dir tests/coverage/all npm run test",
"cover:unit": "nyc --report-dir tests/coverage/unit npm run test:unit",
"cover:functional": "nyc --report-dir tests/coverage/functional -x 'app/repositories' -x 'app/entities' -x 'app/utils' --no-clean npm run test:functional"

我的声纳-project.properties是这样的:

sonar.exclusions=**/node_modules/**,**/*.spec.ts,app/entities/**,dependency-check-report/*,tests/coverage/**/*
sonar.tests=tests
sonar.test.inclusions=tests/**/*
sonar.ts.tslintconfigpath=tslint.json
sonar.typescript.lcov.reportPaths=tests/coverage/all/lcov.info

这个设置有两个问题:

SonarQube 不需要 XML 文件来覆盖 JavaScript,它要求报告采用 lcov 格式。请参阅 SonarQube 的文档:JavaScript Coverage Results Import.

为了生成此 lcov 报告,您可以执行以下操作:

  1. 把你所有的JSON覆盖率数据(browser/harness写入__coverage__全局的)放在一个目录下,默认是.nyc_output
  2. 运行命令nyc report --reporter=lcov --report-dir=.nyc_coverage
  3. 这告诉 nyc 您想要使用 --report-dir 指定目录中的所有文件生成报告(在本例中为 .nyc_coverage)并且您希望报告位于--reporter 指定的格式(在本例中为 lcov
  4. nyc 将创建一个文件夹(默认情况下 .nyc_output)并在其中写入 lcov 文件

如果您愿意,还可以添加额外的记者以保持理智。我通常添加 --reporter=text 这样它也会打印出覆盖范围。

所以你的最终命令可能是:

nyc report \
  --reporter=lcov \
  --reporter=text \
  --report-dir=.nyc_coverage

= 是可选的,命令参数可以在 sub-command 之前,因此您也可以 运行 您记下的命令:

nyc --reporter lcov --reporter text --report-dir .nyc_coverage report

此外,您可以通过在命令行中指定来告诉 SonarQube 报告的位置:

sonar-scanner \
  -Dsonar.projectKey=whatever \
  -Dsonar.javascript.lcov.reportPaths=coverage/lcov.info

或者在项目设置中设置:

Project -> Administration -> JavaScript -> Tests and Coverage -> LCOV Files