Sub topic 15
Running Unit Tests with ng test
The CLI does more than build and serve your app. It also runs unit tests, which are small automated checks that prove one class or component behaves as expected. This chapter covers how ng test works, how to write tests for the counter, todo list and greeting examples from earlier chapters, and how to fix the errors that come up most often.
This chapter assumes you have a project generated with ng new, that you have read the chapters on components, signals, inputs and outputs, and services, and that you know basic test vocabulary such as describe, it and expect.
What ng test Actually Does
Running ng test hands the work to the builder configured under the test target in angular.json. The builder compiles your application code and every file ending in .spec.ts, then gives the result to a test runner. The runner executes the tests and reports the results.
The default runner depends on your CLI version:
| CLI generation | Builder in `angular.json` | Runner | Where tests run |
|---|---|---|---|
| Angular 21 and later | `@angular/build:unit-test` | Vitest | Node with a simulated DOM (jsdom) by default |
| Angular 20 and earlier | `@angular/build:karma` or `@angular-devkit/build-angular:karma` | Karma with Jasmine | A real browser such as Chrome |
To find out which runner your project uses, open angular.json and look at projects.<name>.architect.test.builder. The test code in this chapter uses TestBed plus describe, it, beforeEach and expect with toBe and toContain. Those work in both setups. The runners differ in mocking helpers (vi.fn() in Vitest, jasmine.createSpy() in Jasmine) and in some command-line flags.
Running the Tests
The commands below run the generated test that ships with a new project:
ng test
ng test --watch=falseThe first command starts in watch mode. It stays running and reruns tests each time you save a file. The second command runs once and exits. The exit code is 0 when every test passes and non-zero when any test fails, so this is the form to use in continuous integration (CI) pipelines and scripts.
Other options you will use often:
| Goal | Vitest builder | Karma builder |
|---|---|---|
| Run once, no watching | `ng test --watch=false` | `ng test --watch=false` |
| Collect code coverage | `ng test --coverage` | `ng test --code-coverage` |
| Run without opening a browser window | Default (jsdom) | `ng test --browsers=ChromeHeadless` |
Coverage reports go to a coverage/ folder. Open the HTML report there to see which lines your tests never executed.
Anatomy of a Spec File
The CLI puts each test file next to the code it tests. When you run ng generate component home, you get home.ts and a matching home.spec.ts. The generated root test, app.spec.ts (or app.component.spec.ts in older projects), is a good place to see the basic pattern.
TestBed is Angular's testing utility. It builds a small, isolated Angular environment for each test. You set it up with configureTestingModule, which takes the same kind of imports and providers your app config uses. Then you call createComponent, which returns a fixture. A fixture is a wrapper that gives you access to the component instance (componentInstance), its rendered DOM (nativeElement), and change detection (detectChanges()).
Testing a Component with Signals
The test below covers the Counter component from the signals chapter. Save it as counter.spec.ts next to counter.ts:
import { TestBed } from '@angular/core/testing';
import { Counter } from './counter';
describe('Counter', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [Counter],
}).compileComponents();
});
it('starts at zero', () => {
const fixture = TestBed.createComponent(Counter);
fixture.detectChanges();
const button: HTMLButtonElement = fixture.nativeElement.querySelector('button');
expect(button.textContent).toContain('Count: 0');
});
it('increments and doubles when clicked', () => {
const fixture = TestBed.createComponent(Counter);
fixture.detectChanges();
const button: HTMLButtonElement = fixture.nativeElement.querySelector('button');
button.click();
fixture.detectChanges();
const paragraph: HTMLElement = fixture.nativeElement.querySelector('p');
expect(button.textContent).toContain('Count: 1');
expect(paragraph.textContent).toContain('Double: 2');
});
it('exposes state through signals', () => {
const fixture = TestBed.createComponent(Counter);
const counter = fixture.componentInstance;
counter.increment();
counter.increment();
expect(counter.count()).toBe(2);
expect(counter.double()).toBe(4);
});
});Standalone components go in imports, not declarations. The first two tests check the DOM, which is what the user sees. The third test reads the signals directly, which is faster but couples the test to the component's internals. Use both styles: DOM tests for behavior and signal tests for logic.
Testing Inputs and Outputs
Signal inputs are read-only from inside the component, so you cannot assign them in a test. Set them through the component reference instead. Outputs created with output() have a subscribe method you can listen on:
import { TestBed } from '@angular/core/testing';
import { TodoList } from './todo-list';
describe('TodoList', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [TodoList],
}).compileComponents();
});
it('shows the empty message when there are no items', () => {
const fixture = TestBed.createComponent(TodoList);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Nothing to do.');
});
it('renders one list item per entry and emits on click', () => {
const fixture = TestBed.createComponent(TodoList);
fixture.componentRef.setInput('items', ['Write tests', 'Ship it']);
fixture.detectChanges();
const items: NodeListOf<HTMLLIElement> = fixture.nativeElement.querySelectorAll('li');
expect(items.length).toBe(2);
let emitted: string | undefined;
fixture.componentInstance.selected.subscribe((value) => (emitted = value));
items[1].click();
expect(emitted).toBe('Ship it');
});
});setInput goes through the same path a parent template's binding would, so the @if and @for blocks react exactly as they do in the running app.
Testing Services and Replacing Dependencies
A service with providedIn: 'root' needs no setup. Ask TestBed for it:
import { TestBed } from '@angular/core/testing';
import { GreetingService } from './greeting';
describe('GreetingService', () => {
it('builds a greeting', () => {
const service = TestBed.inject(GreetingService);
expect(service.greet('Ada')).toBe('Hello, Ada!');
});
});When you test a component that depends on a service, you usually want to control what the service returns. Register a replacement in providers, and dependency injection hands it to inject() in place of the real class:
import { TestBed } from '@angular/core/testing';
import { Greeting, GreetingService } from './greeting';
describe('Greeting', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [Greeting],
providers: [
{ provide: GreetingService, useValue: { greet: () => 'Hi from the fake!' } },
],
}).compileComponents();
});
it('renders the message from the service', () => {
const fixture = TestBed.createComponent(Greeting);
fixture.detectChanges();
const heading: HTMLElement = fixture.nativeElement.querySelector('h1');
expect(heading.textContent).toBe('Hi from the fake!');
});
});Greeting reads the service in a field initializer, which runs when the component is constructed. So the override has to be in place before createComponent is called. Configuring it in beforeEach takes care of that.
Common Errors and Their Fixes
| Symptom | Cause | Fix |
|---|---|---|
| The generated `app.spec.ts` fails right after you edit the root template | The default test expects the original welcome text | Update or delete that assertion to match your template |
| Assertions see old values after a click | Change detection was not run | Call `fixture.detectChanges()` after the interaction |
| `NullInjectorError: No provider for HttpClient` | The component injects something the test environment does not provide | Add `provideHttpClient()` and `provideHttpClientTesting()` to `providers` |
| `NullInjectorError` for `ActivatedRoute` or `Router` | A routed component needs router providers | Add `provideRouter([])` to `providers` |
| `'app-x' is not a known element` | The component under test uses a child it never lists in its own `imports` | Fix the component's `imports`. This is a real bug, not a test bug |
| CI job never finishes | `ng test` is in watch mode | Use `ng test --watch=false` |
| Tests pass locally but fail in CI with no browser | Karma is trying to open a desktop Chrome | Use `--browsers=ChromeHeadless` or move to the Vitest builder |
Edge Cases Worth Knowing
- jsdom is not a browser. The Vitest default renders into a simulated DOM. Layout values such as
getBoundingClientRect()return zeros, and some browser APIs are missing. If a test depends on real layout, use an end-to-end tool or configure browser mode for the runner. - Zoneless apps. Recent CLI versions generate zoneless applications. Tests that depend on Zone.js helpers like
fakeAsyncwill not work there unless Zone.js is loaded. Preferawait fixture.whenStable()for async work. - Migrating from Karma. Older projects can stay on Karma. If you switch to Vitest, rewrite Jasmine-specific calls such as
jasmine.createSpyandspyOn. Tests that only useTestBedand basic matchers usually carry over unchanged.
Exercise
You add a test that clicks the Counter button and then checks that the paragraph reads "Double: 2", but the assertion fails and shows "Double: 0". The click handler runs. What is missing, and why?
Show answer
The test needs fixture.detectChanges() after button.click(). The click updates the count signal, and double recomputes when it is read, but the test fixture does not re-render the template on its own. Without another change detection pass, the DOM still shows the first render.
Exercise
Write the provider entry that makes the Greeting component receive a fake GreetingService whose greet method returns "Test", and explain why it must be configured before TestBed.createComponent.
Show answer
Use providers: [{ provide: GreetingService, useValue: { greet: () => 'Test' } }] inside TestBed.configureTestingModule. Greeting calls inject(GreetingService) and greet() in field initializers, which run during construction. That means the injector has to contain the fake before the component is created.
Exercise
Your CI pipeline runs ng test and the job times out even though every test passes. Which command should the pipeline run instead, and what does its exit code tell CI?
Show answer
Run ng test --watch=false. It runs the suite once and exits, with status 0 if every test passed and a non-zero status if any test failed. CI uses that status to mark the job as passed or failed.