Sub topic 11
Using component harnesses
This chapter assumes you can write a TestBed test like the ones in the earlier chapters: create a fixture, call detectChanges(), query the DOM with querySelector, and click elements. Here you replace that manual work with a harness.
What a harness is
A component harness is a class that wraps a component's DOM and exposes it through a small, readable API. Tests call methods such as add() or getCountText() instead of selecting elements. If the template changes later, you update the harness once and the tests keep working.
Harnesses come from the Angular CDK (Component Dev Kit). Install it if the project does not already have it:
npm install @angular/cdkAngular Material ships ready-made harnesses, such as MatButtonHarness. You can also write your own for components in your app.
Writing a harness
This harness wraps the CounterComponent from earlier chapters. It extends ComponentHarness and declares a hostSelector. It uses locatorFor to describe where elements are.
import { ComponentHarness } from '@angular/cdk/testing';
export class CounterHarness extends ComponentHarness {
static hostSelector = 'app-counter';
private readonly countElement = this.locatorFor('[data-testid="count"]');
private readonly addButton = this.locatorFor('button');
async getCountText(): Promise<string> {
return (await this.countElement()).text();
}
async add(): Promise<void> {
await (await this.addButton()).click();
}
}locatorFor returns a function. Calling it finds the element and returns a TestElement. A TestElement has methods such as click(), text(), getAttribute(), and sendKeys(). Every one of them returns a promise.
Using a harness in a test
TestbedHarnessEnvironment.harnessForFixture builds a harness for the component the fixture created:
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';
describe('CounterComponent with a harness', () => {
it('shows the new count after a click', async () => {
const fixture = TestBed.createComponent(CounterComponent);
fixture.componentRef.setInput('step', 5);
const counter = await TestbedHarnessEnvironment.harnessForFixture(
fixture,
CounterHarness,
);
await counter.add();
expect(await counter.getCountText()).toBe('Count: 5');
});
});The test never calls fixture.detectChanges(). The harness environment runs change detection before each read and after each action, then waits for the fixture to become stable.
Finding child components
Use harnessForFixture for the component under test. To find harnesses inside a template, such as Material buttons or your own child components, create a loader with TestbedHarnessEnvironment.loader(fixture). A loader has three lookup methods:
| Method | Returns |
|---|---|
| `getHarness(Type)` | The first match. It throws if nothing matches. |
| `getAllHarnesses(Type)` | An array of every match. |
| `getHarnessOrNull(Type)` | The first match, or `null`. |
A loader only searches inside the fixture's root element. It does not match the root element itself, which is why the component under test uses harnessForFixture.
Harness or direct DOM queries?
Harnesses suit components that you test through several steps, and components with a stable public surface that many tests share. Direct queries stay shorter for a one-off check on a simple template. Both styles work with Vitest, so you can mix them in one project. Use a harness when more than one test needs the same selectors.
Exercise
Why does the harness test above work without calling fixture.detectChanges(), and what must you do in every test that uses a harness?
Show answer
The harness environment runs change detection before it reads or acts on the DOM and waits for the fixture to be stable. Because every harness method returns a promise, the test function must be async and each harness call must be awaited. Without await, assertions run before the actions complete.