Sub topic 13
Coverage and CI
This chapter assumes you can already write and run Vitest specs with ng test, as covered in the earlier chapters. It shows how to measure which code your tests run, and how to run the suite automatically on every push so broken tests never reach the main branch.
What coverage measures
Code coverage is a report of which lines of your source ran while the tests ran. The tool instruments or observes the code, records what executed, and compares that with everything that could execute. Vitest reports four numbers:
| Metric | Question it answers |
|---|---|
| Statements | What share of statements ran at least once? |
| Branches | What share of `if`, `else`, ternary, and `switch` paths were taken? |
| Functions | What share of functions were called at least once? |
| Lines | What share of source lines ran at least once? |
Branch coverage is usually the most informative. A line like return a ? b : c counts as covered when either side runs, but the branch metric shows that one side never did.
Coverage tells you what your tests did not touch. It does not tell you whether the tests check anything. A test that renders a component and asserts nothing still produces coverage.
Turning coverage on
The Angular unit-test builder delegates coverage to Vitest, and Vitest needs a coverage provider package. Install the V8 provider as a development dependency. Use the version that matches your installed Vitest.
npm install --save-dev @vitest/coverage-v8Then run the suite once, without watch mode, and with coverage enabled:
ng test --no-watch --code-coverageThe run prints a table to the terminal and writes report files into a coverage/ folder in the project. Open the HTML report in a browser to see each file with covered and uncovered lines highlighted.
If you want coverage on every run, set it on the test target in angular.json instead of repeating the flag:
{
"test": {
"builder": "@angular/build:unit-test",
"options": {
"runner": "vitest",
"codeCoverage": true,
"codeCoverageReporters": ["text-summary", "html", "lcov"]
}
}
}Each reporter serves a different reader:
text-summaryprints four totals in the terminal.htmlproduces a browsable report for people.lcovproduces a machine-readable file that services such as Codecov, Coveralls, and SonarQube accept.
Coverage slows the run because the code must be observed. Leaving it off by default and enabling it in CI keeps your local loop fast.
Reading a report
Suppose a component has this method:
describeStock(quantity: number): string {
if (quantity === 0) {
return 'Out of stock';
}
return quantity < 5 ? 'Low stock' : 'In stock';
}If your only test passes 10, the report shows the if body as uncovered and the 'Low stock' side of the ternary as an untaken branch. Statement coverage might still look high, because most lines ran. The uncovered branches are the useful finding. They point to two missing tests, one with 0 and one with 3.
Work through a report in this order:
- Sort files by lowest branch coverage.
- Open the file and look for red lines or yellow branch markers.
- Decide whether each gap is behavior you care about. If it is, write a test that reaches it.
- If it is not, such as a trivial getter or generated code, leave it or exclude it on purpose.
Choosing what to include and exclude
By default the report covers files your tests load. A file that no spec imports may be missing from the report entirely, which makes the total look better than it is. Configure the builder so the denominator is honest, and exclude files whose coverage tells you nothing:
{
"test": {
"builder": "@angular/build:unit-test",
"options": {
"runner": "vitest",
"codeCoverage": true,
"codeCoverageExclude": [
"src/main.ts",
"src/**/*.routes.ts",
"src/**/*.config.ts",
"src/**/*.mock.ts"
]
}
}
}Good candidates for exclusion are the bootstrap file, route tables, configuration objects, and test helpers. Do not exclude a component because it is hard to test. That hides the exact code that needs attention.
Thresholds and what they do to behavior
A coverage threshold is a minimum percentage. If a run falls below it, the command exits with a failure code, and a CI job that runs the command fails with it. This turns coverage from a report into a gate. Check the unit-test builder documentation for your Angular version to see how thresholds are named and configured, because this option is newer than the rest.
Thresholds change how people write tests, so set them with care:
- A very high global target, such as 100%, encourages tests written only to light up lines. These tests are brittle and assert little.
- A moderate target with a rule that coverage must not drop is easier to live with. It protects against regressions without forcing busywork.
- Branch coverage is a better gate than line coverage, because it is harder to satisfy without asserting behavior.
What happens in CI
A continuous integration (CI) system is a service that runs commands on a clean machine each time you push code. For tests, the goal is simple: install dependencies, run the suite once, and fail the build if anything fails. The flow looks like this:
Here is a complete GitHub Actions workflow for that flow. Other CI systems use different syntax but the same steps.
name: test
on:
push:
branches: [main]
pull_request:
jobs:
unit-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- run: npm ci
- run: npx ng test --no-watch --code-coverage
- uses: actions/upload-artifact@v4
if: always()
with:
name: coverage-report
path: coverage/Points worth understanding in this file:
npm ciinstalls exactly whatpackage-lock.jsonspecifies and fails if the lock file andpackage.jsondisagree.npm installcan silently change versions, so usenpm ciin CI.--no-watchmakes the run finish. Watch mode would wait for file changes and hang the job until it times out.if: always()uploads the report even when tests fail. That is when you most want to read it.cache: npmreuses downloaded packages between runs and shortens the install step.- Use
npx ng, or a script inpackage.json, so the CI machine uses the CLI version installed in the project.
Making CI runs trustworthy
A suite that passes locally and fails in CI usually has one of a few causes. Check these first.
- Leaked fake timers. If a spec calls
vi.useFakeTimers()and never restores real timers, later specs in the same file can hang or fail depending on order. Always callvi.useRealTimers()inafterEach, as shown in the timers chapter. - Unverified HTTP. A missing
http.verify()lets unexpected requests slip by. Specs then pass or fail depending on timing. - Time and locale. Code that formats dates or numbers can produce different text on a machine with a different time zone or locale. Pass explicit values in tests, or freeze the date with
vi.setSystemTime. - Shared state between specs. A module-level variable or a service provided in root and mutated by one spec can affect another.
TestBedresets between tests, but your own globals are not reset. - Environment differences. The unit-test builder runs specs in a simulated DOM by default. If you opt into a real browser, CI needs a headless browser available. Pin your Node version so the CI and local runs match.
Putting the commands behind scripts
Teams often add short scripts to package.json so that humans and CI run identical commands:
{
"scripts": {
"test": "ng test",
"test:ci": "ng test --no-watch --code-coverage"
}
}The workflow step then becomes npm run test:ci. When you change the flags later, you edit one line and both local and CI use the new behavior.
A practical policy
A simple policy covers most projects:
- Run
ng testin watch mode while developing, without coverage. - Run
test:cion every pull request and require it to pass before merge. - Publish the HTML or
lcovreport so reviewers can see what a change left untested. - Use coverage to find gaps in behavior you chose to care about in the "what to test" chapter, not as a goal in itself.
Exercise
Your CI job runs ng test --code-coverage and the job never finishes, though the tests pass on your laptop. Name the likely cause and give the corrected command. Then explain why a project at 95% line coverage might still have a poorly tested if/else method.
Show answer
The run is in watch mode, which waits for file changes instead of exiting, so the CI job hangs until it times out. Use ng test --no-watch --code-coverage. A line can count as covered when only one path through it ran. For a method with an if/else, a single test that takes the if path executes most lines, so line coverage stays high while the else branch is never exercised. Branch coverage exposes this gap, so it is the better metric to review and to gate on.
Exercise
A teammate adds a spec with vi.useFakeTimers() and no cleanup. Specs later in the file start failing only in CI. What change fixes it, and where does it go?
Show answer
Add afterEach(() => { vi.useRealTimers(); }); to the spec file, importing afterEach from vitest. Fake timers stay active until restored, so later specs run with a frozen clock. Cleanup in afterEach runs even when a test fails, which keeps each spec independent of order.