'How to get exact code coverage in sonarcloud for angular

I am trying to produce code coverage report in sonarcloud for angular-12. Could someone help me how to configure azure pipeline for generating correct code coverage percentage. Currently I am configurating as below,

  sonar.exclusions=**/node_modules/**
  sonar.tests=$(System.DefaultWorkingDirectory)/projects/project_name/src
  sonar.sources=$(System.DefaultWorkingDirectory)/projects/project_name/src
  sonar.test.inclusions=$(System.DefaultWorkingDirectory)/projects/project_name/src/**/*.spec.ts
  sonar.typescript.lcov.reportPaths=$(System.DefaultWorkingDirectory)/coverage/project_name/lcov.info 

I am expecting same code coverage percentage as we get in ng test --code-coverage command.But unfortunately, percentage is showing in sonar cloud seems bit different.



Solution 1:[1]

By default, the Angular test coverage report will measure coverage of files that were loaded during the test as opposed to all source files, whereas SonarCloud will use all source files (as you defined your Sonar configuration) as the denominator for calculating test coverage.

An issue regarding this has been open since 2016.

To get a more accurate report with ng test --code-coverage I updated the following files:

  1. src/test.ts, changing this:
const context = require.context('./', true, /\.spec\.ts$/);

into this:

const context = require.context('./app/', true, /\.ts$/);
  1. angular.json ,adding "codeCoverageExclude": ["**/*.module.ts"], to the projects.<your-project-name>.architect.test.options object.
"test": {
  "builder": "@angular-devkit/build-angular:karma",
  "options": {
    ...
    "codeCoverageExclude": ["**/*.module.ts"],
    ...
  }
},
  1. tsconfig.spec.json, adding '**/*.ts' as the first element of the "include" array.
  "include": [
    "**/*.ts",
    "src/**/*.spec.ts",
    "src/**/*.d.ts"
  ]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Touré Holder