9

I am trying to figure out how to include all my .ts sources in the generated coverage report from the angular CLI. Currently I am only getting coverage for files that have an associated spec with tests against.

I have tried adding the includeAllSources flag to my karma.conf.js file but this made no difference.

Whats the correct approach here? I am using Angular CLI 6.1.5

Thanks

mindparse
  • 6,115
  • 27
  • 90
  • 191

2 Answers2

20

The simplest solution that worked for me on Angular(v6) was just adding a app.module.spec.ts file to compliment your app.module.ts and within that .spec include the following code

import './app.module';

Apparently due to the fact app.module.ts is the root of your application including a .spec for that module will result in the inclusion of all your files during code coverage (ng test --code-coverage)

Narm
  • 10,677
  • 5
  • 41
  • 54
  • Used same Workaround as the answer above in my Angular 8 project. For each lazy loaded module I added a seperate testfile analogous to app.module.spec.ts. – Kathrin Sep 24 '19 at 06:05
  • I am having a small Angular library. At the end of the `test.ts`, I've added an export: `export * from './public-api';` – Volker Andres Feb 24 '22 at 14:09
5

Solution provided by Narm is really great, however still not ideal, as requires importing manually at least all the lazy loaded modules + root one to the tests and also on big projects there are almost always some non-used/forgotten components which are not part of any production code and which will leave in the source code for ever untested/undiscovered.

Solution:

https://github.com/kopach/karma-sabarivka-reporter.

To use it → install npm install --save-dev karma-sabarivka-reporter

And update karma.conf.js as described here https://github.com/kopach/karma-sabarivka-reporter#-usage

After this – all files matching pattern will be included into final coverage result

Ihor
  • 3,219
  • 2
  • 18
  • 20
  • 1
    This works great. I had to add `require('karma-sabarivka-reporter')` to the `plugins` array in `karma.conf.js` to make it work. The Lines coverage went from 434/4201 to 38/6589, which is a little weird because the lines covered should not have changed. However, when i `cloc src/app` my app, it says 11,745 lines of TypeScript. So it seems there are still a lot of LOC not being counted. – alexkelbo Jan 22 '20 at 11:43
  • 1
    @alexraasch, please, make sure your configuration doesn't include "too much". Only needed source code files should be included. See Usage section of plugin's Readme page. As for LOC – try karma-html-reporter, and go through generated HTML reports to see what's exactly added to coverage. – Ihor Jan 29 '20 at 20:14
  • curious how people are handling this with jest? Somewhat similar in the jest.config file? – Winnemucca Jun 26 '20 at 20:58