Nx、Angular、Jest 和 Sonar

Nx, Angular, Jest and Sonar

我正在寻找与 Nx (13.4.1) Angular (13.1) 工作区一起使用的方法,使用 Jest 进行 运行 单元测试。我想为每个库单独生成并发布单元测试 运行 结果和覆盖率报告到 SonarQube 服务器。

创建 Nx Angular 具有多个 Angular 库的工作区 https://nx.dev/angular

(对于本食谱,库文件夹结构必须采用 ./libs/my-scope/my-library 的形式)

(可选)通过Docker

创建本地SonarQube服务器
docker run -d --name sonarqube -p 9000:9000 sonarqube:latest

(将凭据从 admin / admin 更改为其他) https://www.sonarqube.org/features/deployment/

设置 SonarQube 扫描仪

快速入门文章 - 为 Angular 设置 SonarQube https://codeburst.io/setup-sonarqube-for-angular-application-locally-in-three-easy-steps-8f31e339ac19

npm install -g sonar-scanner

修改每个库中的jest.config.js

module.exports = {
  displayName: 'my-scope-my-library',
  preset: '../../../jest.preset.js',
  setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
  globals: {
    'ts-jest': {
      tsconfig: '<rootDir>/tsconfig.spec.json',
      stringifyContentPathRegex: '\.(html|svg)$',
    },
  },
  coverageReporters: ["clover", "json", "lcov", "text", "text-summary"],
  collectCoverage: true,
  testResultsProcessor: "jest-sonar-reporter",
  coverageDirectory: '../../../coverage/libs/my-scope/my-library',
  transform: {
    '^.+.(ts|mjs|js|html)$': 'jest-preset-angular',
  },
  transformIgnorePatterns: ['node_modules/(?!.*.mjs$)'],
  transformIgnorePatterns: ['node_modules/(?!.*\.mjs$)'],
  snapshotSerializers: [
    'jest-preset-angular/build/serializers/no-ng-attributes',
    'jest-preset-angular/build/serializers/ng-snapshot',
    'jest-preset-angular/build/serializers/html-comment',
  ],
};

(添加了这三行)

  coverageReporters: ["clover", "json", "lcov", "text", "text-summary"],
  collectCoverage: true,
  testResultsProcessor: "jest-sonar-reporter",

安装 jest-sonar-reporter npm 包

npm install --save-dev jest-sonar-scanner

在工作区根目录中创建 sonar-project.properties

sonar.projectBaseDir=.
sonar.sourceEncoding=UTF-8
sonar.exclusions=
sonar.inclusions=**/*.ts, **/*.scss, **/*.html
sonar.test.inclusions=**/*.spec.ts

创建 bash 脚本以遍历作用域和库

scopes=$(ls libs)
for scope in $(echo $scopes); do
  libs=$(ls libs/$scope)
  for lib in $(echo $libs); do
    echo "$scope -- $lib"
    nx test "$scope-$lib" --code-coverage || true
    mv test-report.xml coverage/libs/$scope/$lib

    # run sonar scanner to anaylize and publish results
    sonar-scanner \
      -Dsonar.login=$SONAR_LOGIN \
      -Dsonar.host.url=$SONAR_HOST_URL \
      -Dsonar.projectKey="optional-prefix-$scope-$lib" \
      -Dsonar.sources=libs/$scope/$lib/src \
      -Dsonar.tests=libs/$scope/$lib/src \
      -Dsonar.javascript.lcov.reportPaths=coverage/libs/$scope/$lib/lcov.info \
      -Dsonar.testExecutionReportPaths=coverage/libs/$scope/$lib/test-report.xml

  done
done