I am running the following command to unit test and generate code code coverage report.
ng test --code-coverage
It is writing code coverage re
Here is the way to do this:
Add client
section to your karma.conf.js
like this:
plugins: [
...
],
client: {
codeCoverage: config.angularCli.codeCoverage
},
files: [
...
],
Change your test.ts
to require files according to codeCoverage
parameter:
let context;
if (__karma__.config.codeCoverage) {
context = require.context('./app/', true, /\.ts/);
} else {
context = require.context('./app/', true, /\.spec\.ts/);
}
context.keys().map(context);
UPDATE:
Since Angular CLI 1.5.0
additional steps are required:
Next to tsconfig.spec.json
add tsconfig-cc.spec.json
file with the following content:
{
"extends": "./tsconfig.spec.json",
"include": [
"**/*.ts"
]
}
In your angular-cli.json
add the following to apps
array:
{
"root": "src/",
"polyfills": "polyfills.ts",
"test": "test.ts",
"testTsconfig": "tsconfig-cc.spec.json"
}
In your karma.conf.js
add the following to angularCli
section:
app: config.angularCli.codeCoverage ? '1' : '0'
eventually it should look something like this:
angularCli: {
environment: 'dev',
app: config.angularCli.codeCoverage ? '1' : '0'
},
So what's happening here?
Apparently they have fixed Angular compiler plugin and it takes the file globs from tsconfig.spec.json
now. As long as we include only **/*.spec.ts
in tsconfig.spec.json
these are the only files that will be included in coverage.
The obvious solution is making tsconfig.spec.json
include all the files (in addition to require.context
). However, this will slow down all the tests even when running without coverage (which we don't want to).
One of the solutions is using the ability of angular-cli
to work with multiple apps.
By adding another entry into apps
array, we're adding another configuration for "another" (which is actually the same one) app.
We strip out all the irrelevant information in this config, leaving just the test configuration, and put another tsconfig
which includes all the ts
files.
Finally, we're telling angular-cli
karma
plugin to run the tests with the configuration of the second app (index 1
) in case it is running with code coverage and run with the configuration of the first app (index 0
) if it is running without code coverage.
Important note: in this configuration I assume you have only one application in .angular-cli.json
. In case you have more you have to adjust indexes accordingly.