Sub topic 13
Running unit tests with ng test
This chapter assumes you can read TypeScript, know what a standalone component and a service are, and have a workspace created with ng new. It also assumes you have seen angular.json and the tsconfig files. Here you will learn what ng test does, how the files it uses connect, and how to fix the errors that come up most often.
What ng test does
ng test is a CLI command. It looks up the test target of your project in angular.json, runs the builder named there, and passes it the options you configured.
The builder, not the CLI, does the real work. It compiles your *.spec.ts files and your application code, starts a test runner, and reports the results.
The runner depends on your Angular version. Workspaces created with older CLI versions use Karma as the runner and Jasmine as the framework for writing tests. Karma starts a real browser, usually Chrome, and runs the tests inside it. Newer CLI versions can use Vitest instead. Check your own angular.json to see which one you have. The examples below use Jasmine syntax. In Vitest the same ideas apply, but the matcher imports and a few globals differ.
The files that matter
Three places control your tests.
| Location | Role |
|---|---|
| `test` target in `angular.json` | Names the builder and sets options such as `include`, `polyfills` and `styles` |
| `tsconfig.spec.json` | Compiles specs; adds test types such as `jasmine` and includes `src/**/*.spec.ts` |
| `*.spec.ts` files | The tests, kept next to the code they test |
The test target looks roughly like this. The builder name varies by version, so treat this as the shape and not the exact text.
{
"test": {
"builder": "@angular/build:karma",
"options": {
"tsConfig": "tsconfig.spec.json",
"polyfills": ["zone.js", "zone.js/testing"],
"styles": ["src/styles.css"]
}
}
}The zone.js/testing polyfill is needed in zone-based projects. Without it, helpers such as fakeAsync fail.
tsconfig.spec.json extends tsconfig.json. It is separate so that test-only types, such as jasmine, do not leak into the application build. The application's own tsconfig.app.json excludes *.spec.ts for the same reason.
Newer Karma setups need no karma.conf.js. If you need to customize browsers or reporters, generate one with ng generate config karma.
Your first run
Running ng test with no arguments starts the runner in watch mode. It opens a Chrome window, runs every spec, and re-runs affected tests when you save a file. This works well while you develop.
On a build server there is no display and no one to close the process. Use a headless browser and turn off watching:
ng test --no-watch --browsers=ChromeHeadlessAdd --code-coverage to write a coverage report to the coverage/ folder. Add --include to limit which specs run. It accepts a glob relative to the project root:
ng test --include='src/app/products/**/*.spec.ts'The command exits with a non-zero status when any test fails. CI systems rely on that exit code to mark the build as failed.
Anatomy of a spec
A spec file groups tests with describe, defines each test with it, and checks results with expect. The service below keeps a list of product names. The spec follows it.
// src/app/products/product.ts
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class ProductService {
private names: string[] = [];
add(name: string): void {
const trimmed = name.trim();
if (trimmed) {
this.names.push(trimmed);
}
}
list(): readonly string[] {
return this.names;
}
}// src/app/products/product.spec.ts
import { TestBed } from '@angular/core/testing';
import { ProductService } from './product';
describe('ProductService', () => {
let service: ProductService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(ProductService);
});
it('adds a trimmed name', () => {
service.add(' Lamp ');
expect(service.list()).toEqual(['Lamp']);
});
it('ignores blank names', () => {
service.add(' ');
expect(service.list().length).toBe(0);
});
});TestBed is Angular's test harness. It builds a small injector, just like a real application would. Each test gets a fresh TestBed, so state from one test does not leak into the next.
Note the file name: ng generate service products/product creates product.ts and product.spec.ts in newer CLI versions, and product.service.ts in older ones. The spec's import path must match whichever name you have.
Testing a standalone component
A standalone component declares its own dependencies. In a test, you put the component itself in imports, not declarations.
// src/app/counter/counter.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-counter',
standalone: true,
template: `
<button type="button" (click)="increment()">Add</button>
<p class="value">{{ count }}</p>
`,
})
export class CounterComponent {
count = 0;
increment(): void {
this.count++;
}
}// src/app/counter/counter.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { CounterComponent } from './counter';
describe('CounterComponent', () => {
let fixture: ComponentFixture<CounterComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [CounterComponent],
}).compileComponents();
fixture = TestBed.createComponent(CounterComponent);
fixture.detectChanges();
});
it('starts at zero', () => {
const text = fixture.nativeElement.querySelector('.value').textContent;
expect(text).toBe('0');
});
it('shows the new count after a click', () => {
fixture.nativeElement.querySelector('button').click();
fixture.detectChanges();
const text = fixture.nativeElement.querySelector('.value').textContent;
expect(text).toBe('1');
});
});The fixture wraps the component and its DOM. Angular does not update the DOM on its own in a test. You call fixture.detectChanges() to run change detection. Forgetting that call is the most common reason a test sees stale text.
Isolating and focusing tests
While you work on one test, you can narrow the run. Change it to fit, or describe to fdescribe, to run only that block. Use xit and xdescribe to skip tests.
Always remove these prefixes before committing. A leftover fit makes the suite pass while most tests never run, and the runner will not warn you. Many teams add a lint rule or a CI check to catch this.
Common errors and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| `NullInjectorError: No provider for HttpClient` | Component or service needs a provider the test did not supply | Add the provider in `configureTestingModule`, for example `provideHttpClient()` and `provideHttpClientTesting()` |
| `Cannot find name 'describe'` in the editor | Test types are missing from the TypeScript config | Check that `tsconfig.spec.json` lists the test framework in `types` |
| `Can't bind to 'ngModel'` or an unknown element | A template dependency is not imported | Add it to the component's `imports`, or to the test's `imports` for a module-based component |
| Test passes locally, fails in CI | CI has no display or runs a different Chrome | Use `--browsers=ChromeHeadless` and pin the browser |
| Command never exits in CI | Watch mode is still on | Add `--no-watch` |
| Text in the DOM is stale | Change detection did not run | Call `fixture.detectChanges()` after the action |
| Whole suite runs but few tests appear | A `fit` or `fdescribe` is left in | Search for and remove focused tests |
A final point on failures: if the compile step fails, no tests run at all. A type error in any spec file, even one you did not touch, can stop the whole run. Read the first error in the terminal and fix it before looking at later ones.
Exercise
Your CI job runs ng test and hangs until it times out, even though all tests pass. Which command line fixes it, and why?
Show answer
Run ng test --no-watch --browsers=ChromeHeadless. By default ng test runs in watch mode, so the process stays alive waiting for file changes after the tests finish. --no-watch makes it exit once the run completes, and ChromeHeadless lets the browser start on a machine with no display.
Exercise
A component spec checks that a heading shows the text "Hello, Ada" after you set name = 'Ada' on the component instance. The assertion fails and still sees the old text. What is missing, and where do you add it?
Show answer
Change detection did not run. Call fixture.detectChanges() after setting the property and before reading the DOM. Angular does not update a test fixture's view automatically.