Sub topic 11
Using component harnesses
This chapter assumes you can already write a test with TestBed, ComponentFixture, and DOM queries, as covered in the earlier chapters. It adds a second way to drive a component: a harness. A harness is a class that wraps a component's DOM and exposes the actions a user takes, such as clicking or reading a label. You need the Component Dev Kit (CDK) package for this: npm install @angular/cdk. The CDK is a library of Angular building blocks, and Angular Material is built on it.
The problem harnesses solve
Direct DOM tests repeat selectors and call fixture.detectChanges() after every action. When the template changes, every test that mentions the old selector breaks, even if the component's behavior did not change.
A harness moves that knowledge into one class:
- Tests call methods like
increment()andgetCountText(). - Only the harness knows that the count lives in
[data-testid="count"]. - The harness API is asynchronous, so the environment runs change detection and waits for the fixture to settle before each step. You do not call
detectChanges()yourself.
The same idea lets library authors ship harnesses for their components. Angular Material does this: MatButtonHarness, MatInputHarness, MatSelectHarness, and others.
The pieces of the harness API
| Piece | Where it comes from | Purpose |
|---|---|---|
| `ComponentHarness` | `@angular/cdk/testing` | Base class you extend to write a harness |
| `hostSelector` | static property on your harness | CSS selector that identifies the component's host element |
| `locatorFor`, `locatorForOptional`, `locatorForAll` | methods on `ComponentHarness` | Find elements or child harnesses inside the host |
| `TestElement` | returned by locators | Wrapper around an element with async methods such as `click()`, `text()`, `getAttribute()`, `sendKeys()` |
| `TestbedHarnessEnvironment` | `@angular/cdk/testing/testbed` | Connects harnesses to a `TestBed` fixture |
| `HarnessLoader` | returned by `TestbedHarnessEnvironment.loader(fixture)` | Finds harnesses by class: `getHarness`, `getAllHarnesses`, `getHarnessOrNull` |
Writing a harness
The examples use the counter from earlier in this tutorial. It is repeated here so the chapter runs on its own.
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 harness lives in its own file, next to the component:
import { ComponentHarness } from '@angular/cdk/testing';
export class CounterHarness extends ComponentHarness {
static hostSelector = 'app-counter';
private readonly button = this.locatorFor('button');
private readonly display = this.locatorFor('[data-testid="count"]');
async increment(): Promise<void> {
const button = await this.button();
await button.click();
}
async getCountText(): Promise<string> {
const display = await this.display();
return display.text();
}
}Three things to notice:
locatorForreturns a function, not an element. You call that function inside a method, so the lookup happens at the moment you need it, against the current DOM.- Every
TestElementmethod returns a promise. Forgettingawaitis the most common harness bug, and the test may pass or fail for the wrong reason. - The harness exposes behavior, not elements. Tests never see a
HTMLButtonElement.
Using the harness in a test
For the component you create yourself, use harnessForFixture:
import { TestBed } from '@angular/core/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { describe, it, expect, vi } from 'vitest';
import { CounterComponent } from './counter.component';
import { CounterHarness } from './counter.harness';
describe('CounterComponent with a harness', () => {
it('adds the step to the count', async () => {
const fixture = TestBed.createComponent(CounterComponent);
fixture.componentRef.setInput('step', 5);
const onChanged = vi.fn();
fixture.componentInstance.changed.subscribe(onChanged);
const counter = await TestbedHarnessEnvironment.harnessForFixture(
fixture,
CounterHarness,
);
await counter.increment();
expect(await counter.getCountText()).toContain('Count: 5');
expect(onChanged).toHaveBeenCalledWith(5);
});
});There is no fixture.detectChanges() call. The environment runs change detection before each harness operation and waits for the fixture to become stable afterward, so the first render also happens through the harness.
Vitest features still work as usual. vi.fn() records the emitted output, and the setInput call is the same one you used without a harness.
Why `harnessForFixture` and not `loader`
TestbedHarnessEnvironment.loader(fixture) creates a loader rooted at the fixture's host element. A loader searches the descendants of its root. The component under test is the root itself, so loader.getHarness(CounterHarness) would not find it.
Use this rule:
harnessForFixture(fixture, HarnessClass)when the fixture is the component the harness describes.loader(fixture)when the fixture's template contains the components you want to find.
Finding several harnesses in a host component
A host component makes the loader useful. This one renders two counters:
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { describe, it, expect } from 'vitest';
import { CounterComponent } from './counter.component';
import { CounterHarness } from './counter.harness';
@Component({
selector: 'app-host',
imports: [CounterComponent],
template: `
<app-counter [step]="2" />
<app-counter />
`,
})
class HostComponent {}
describe('two counters', () => {
it('keeps the counts independent', async () => {
const fixture = TestBed.createComponent(HostComponent);
const loader = TestbedHarnessEnvironment.loader(fixture);
const [first, second] = await loader.getAllHarnesses(CounterHarness);
await first.increment();
await first.increment();
await second.increment();
expect(await first.getCountText()).toBe('Count: 4');
expect(await second.getCountText()).toBe('Count: 1');
});
});getAllHarnesses returns the harnesses in document order. If the component might be absent, use getHarnessOrNull. The plain getHarness throws when it finds no match, which makes a missing element a clear failure.
Using Angular Material harnesses
Material harnesses work the same way. This snippet needs @angular/material installed, and the host component must render a mat-button:
import { MatButtonHarness } from '@angular/material/button/testing';
const loader = TestbedHarnessEnvironment.loader(fixture);
const save = await loader.getHarness(MatButtonHarness.with({ text: 'Save' }));
await save.click();
expect(await save.isDisabled()).toBe(true);with({ text: 'Save' }) builds a filter, so you pick one button out of several without a CSS selector. Material's internal markup can change between releases, but the harness API stays stable. That stability is the main reason to prefer these harnesses over hand-written selectors for library components.
Overlay content such as menus, dialogs, and select options is rendered outside the fixture's element. For those, use TestbedHarnessEnvironment.documentRootLoader(fixture), which searches the whole document.
Harness or direct DOM test?
| Situation | Better choice |
|---|---|
| Several tests interact with the same component | Harness |
| The component belongs to a library that ships harnesses | The library's harness |
| One quick check of rendered text | Direct DOM query |
| You need exact control over when change detection runs | Direct DOM test with `detectChanges()` |
| Test reads like a user story (click, type, read) | Harness |
Harnesses trade a little setup for tests that survive template changes. A single one-off test rarely repays that cost.
Common errors
- Missing
await.counter.increment();withoutawaitreturns before the click finishes, so the next assertion sees stale state. A lint rule for floating promises catches this. - Asserting on a promise.
expect(counter.getCountText()).toBe(...)compares a promise to a string. Await the call first. - Wrong loader.
loader.getHarnesson the fixture of the component itself fails with a "could not find" error. UseharnessForFixture. - Mixed
hostSelectorand template. IfhostSelectordoes not match the component's selector, no harness is found even though the component rendered. - Hanging tests with fake timers. The environment waits for the fixture to stabilize, and pending timers can hold it up. If a harness test hangs after
vi.useFakeTimers(), move the timer-related assertions to a direct fixture test, or advance the timers before the next harness call.
Exercise
Extend CounterHarness with a method getStepLabel that reads the text of a new element <span data-testid="step"> in the template. Which two lines in the harness change, and does the test need any detectChanges() call?
Show answer
Add a field private readonly stepLabel = this.locatorFor('[data-testid="step"]'); and a method async getStepLabel(): Promise<string> { return (await this.stepLabel()).text(); }. The test needs no detectChanges() call, because the harness environment runs change detection and waits for stability before each operation.
Exercise
A test calls const counter = await loader.getHarness(CounterHarness); where loader = TestbedHarnessEnvironment.loader(TestBed.createComponent(CounterComponent)). It throws an error saying no harness matched. Why, and what is the fix?
Show answer
The loader searches inside the fixture's host element, and the app-counter host is the root, not a descendant. Replace the call with TestbedHarnessEnvironment.harnessForFixture(fixture, CounterHarness), or wrap the counter in a host component and use the loader on that fixture.