Sub topic 2
Setting up and running tests with ng test
This chapter covers how Angular's ng test command runs your specs with Vitest. It assumes you know basic TypeScript, Angular standalone components and dependency injection, and signals with input() and output(). It also assumes you can use npm and the Angular CLI. By the end you will be able to configure the test target, run tests in several modes, and diagnose the most common setup failures.
What ng test does
ng test is the Angular CLI command that builds your spec files and runs them. It does not run Vitest directly. The CLI delegates to a builder, which is a package that knows how to perform one kind of task. For tests, that builder is @angular/build:unit-test. The builder compiles your TypeScript with the same toolchain as ng build, then hands the compiled specs to a runner. The runner is the program that executes tests and reports results. Here the runner is Vitest.
This split has a practical consequence. Angular compiles your components, so templates, signals, and decorators work in tests the same way they do in the app. Vitest then provides describe, it, expect, and vi.
The test target in angular.json
The angular.json file describes your workspace. Each project has an architect section with named targets such as build, serve, and test. A target pairs a builder with its options. The test target for Vitest looks like this:
{
"test": {
"builder": "@angular/build:unit-test",
"options": {
"runner": "vitest"
}
}
}The runner option picks the test runner. Setting it to vitest tells the builder to run specs through Vitest. A new project created with a recent Angular CLI usually has this target already. If you are moving an older project, replace the old test target with this one.
In a real file, the snippet sits under projects, then your project name, then architect. If you paste it at the wrong level, the CLI reports that the target is missing or invalid.
Common target options
The builder accepts more options than runner. The exact set depends on your Angular version, so check the output of ng test --help for your installed CLI. The options most projects reach for are:
| Option | Purpose |
|---|---|
| `runner` | Selects the test runner. Use `vitest`. |
| `include` | Glob patterns for which spec files to run. |
| `watch` | Re-runs tests when files change. |
| `coverage` | Collects code coverage. |
Treat this table as a guide to what to look for, not a complete reference. Option names and defaults can change between releases.
Installing the dependencies
Vitest is a separate npm package. The builder needs it to be installed in your project. A new project generated by the CLI normally adds it for you. If you add testing to an existing project, install it as a development dependency:
npm install --save-dev vitestA DOM implementation is also needed, because Angular components render into a document. By default the Vitest runner in Angular runs tests in a simulated DOM provided by a library such as jsdom. Simulated means it behaves like a browser document but runs inside Node.js. If the builder reports a missing package, install the one it names. The error message tells you which one.
npm install --save-dev jsdomRunning tests
Run all specs from the project root:
ng testIn a terminal the command usually starts in watch mode. Watch mode keeps the process alive and re-runs affected tests when you save a file. This is the mode you want while developing.
In a CI job, you want the opposite: run once, print results, and exit with a status code. Turn watch off for that:
ng test --no-watchThe exit code is zero when every test passes and non-zero when any test fails. Continuous integration (CI) systems use this code to decide whether a build succeeded.
Running a subset of specs
Large projects take longer to test. Use --include to restrict which files run:
ng test --include='src/app/counter/**/*.spec.ts'Quote the glob so your shell does not expand it before the CLI sees it. You can also run a single spec file by giving its path.
Choosing a project
A workspace can hold several applications and libraries. Name the project to test only that one:
ng test my-libraryWithout a name, the CLI tests the default project or every project that defines a test target, depending on your workspace configuration.
Where specs live and how they are found
By convention, a spec file sits next to the code it tests and ends in .spec.ts. A test for counter.component.ts is counter.component.spec.ts. The builder's default include pattern matches **/*.spec.ts under your source root. A file named counter.test.ts or placed outside the source root is not found unless you change include. If ng test reports that no tests were found, check the file name and location first.
Imports and globals
Vitest can expose describe, it, and expect as globals, which means you can use them without importing. The examples in this tutorial import them explicitly:
import { describe, it, expect, vi } from 'vitest';Explicit imports are the safer choice. Your editor and the TypeScript compiler can see where each name comes from, and you do not depend on a global type setting in tsconfig.spec.json. If you omit the import and the globals are not configured, you get errors such as describe is not defined or a type error that says the name cannot be found.
A first test to confirm the setup
Create a small component and a spec to check that everything is wired correctly. This is the counter component that later chapters build on:
import { Component, input, output, signal } from '@angular/core';
@Component({
selector: 'app-counter',
template: `
<p data-testid="count">Count: {{ count() }}</p>
<button type="button" (click)="increment()">Add</button>
`,
})
export class CounterComponent {
readonly step = input(1);
readonly changed = output<number>();
protected readonly count = signal(0);
increment() {
this.count.update((c) => c + this.step());
this.changed.emit(this.count());
}
}The next spec is deliberately minimal. It only checks that the component can be created, which proves that compilation, the DOM, and the runner all work:
import { TestBed } from '@angular/core/testing';
import { describe, it, expect } from 'vitest';
import { CounterComponent } from './counter.component';
describe('CounterComponent setup', () => {
it('creates the component', () => {
const fixture = TestBed.createComponent(CounterComponent);
expect(fixture.componentInstance).toBeTruthy();
});
});Save the files as counter.component.ts and counter.component.spec.ts in the same folder, then run ng test --no-watch. A passing run lists the spec and reports one passed test. Later chapters explain TestBed and fixtures in detail. For now, treat them as the way to create a component inside a test.
Reading the output
A Vitest run prints each spec file with its tests, then a summary with counts of passed and failed tests and the elapsed time. A failure shows the test name, the failed expect line, and the expected and received values. Read the received value first. It tells you what the code did, and the expected value tells you what you assumed.
Compile errors appear before any test runs. A TypeScript error in a spec or in the code it imports stops the run, because the builder cannot produce output. Fix the first error in the list. Later errors are often a result of the first.
Common setup errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Cannot find a test target` | The project has no `test` target in `angular.json`. | Add the target shown earlier. |
| `Cannot find package 'vitest'` | Vitest is not installed. | Run `npm install --save-dev vitest`. |
| A message about a missing DOM package | The simulated DOM library is not installed. | Install the package the message names, such as `jsdom`. |
| `No test files found` | The file name or location does not match `include`. | Rename to `*.spec.ts` or change `include`. |
| `describe is not defined` | Globals are not enabled and there is no import. | Import from `vitest`. |
| The process never exits in CI | Watch mode is on. | Pass `--no-watch`. |
Checking your understanding
Exercise
Your CI job runs ng test and never finishes, although all tests pass locally. What is the likely cause, and what command fixes it?
Show answer
ng test starts in watch mode in some environments, so the process stays alive waiting for file changes. Run ng test --no-watch so the run ends after one pass and returns an exit code.
Exercise
You add orders.spec.ts in a folder outside src, and ng test reports no tests found. Name two ways to fix this.
Show answer
Move the spec under the source root next to the code it tests, or change the test target's include option so it matches the file's location. Keeping specs beside their code is the convention.