← Back to Angular, page 5

angular-0087 · Hard senior

What are component harnesses, why are they better than querying the DOM in tests, and how do you write your own?

A component harness is a class that wraps a component's DOM behind an API such as increment() or getValue(). Tests use that API, not CSS selectors, so internal markup can change without breaking tests. Angular Material ships harnesses for its components, and you write your own by extending ComponentHarness with a hostSelector.

Full answer

Tests that query the DOM directly (fixture.nativeElement.querySelector('.btn-primary')) break when markup or class names change, even if behaviour is the same. They also repeat the same selectors in many tests.

A harness puts those details in one class:

  • It extends ComponentHarness from @angular/cdk/testing.
  • It has a static hostSelector that finds the component's host element.
  • It defines locators in terms of the DOM with this.locatorFor('button.inc') and exposes methods in terms of behaviour: increment(), getValue().
  • Methods are asynchronous. The harness environment waits for change detection and pending work (fixture.whenStable) after each action, so you do not need fixture.detectChanges() or tick() for it.
  • A static with(options) method returns a HarnessPredicate to find a specific instance, for example the counter with a given label.

Using it in a test:

const loader = TestbedHarnessEnvironment.loader(fixture); const counter = await loader.getHarness(CounterHarness); await counter.increment(); expect(await counter.getValue()).toBe(1);

Benefits:

  • The same harness works with unit tests (TestbedHarnessEnvironment), and with end to end tests in Protractor-like environments through other HarnessEnvironment implementations.
  • Library authors ship harnesses with components (Angular Material does: MatButtonHarness, MatSelectHarness, MatDialogHarness). Your tests then do not depend on Material's internal DOM, so upgrades are safe.
  • Nested harnesses: a form-field harness can return the harness of the control inside it with getControl().

Limits: harnesses add an abstraction, so they pay off for shared components that many tests touch, not for a one-off component. For overlays (menus, dialogs), use documentRootLoader since the content lives outside the fixture.

typescript
// file: counter.component.ts
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-counter',
  template: `
    <span class="value" data-test="value">{{ count() }}</span>
    <button type="button" data-test="inc" (click)="count.set(count() + 1)">Add one</button>
    <button type="button" data-test="reset" (click)="count.set(0)">Reset</button>
  `,
})
export class CounterComponent {
  readonly count = signal(0);
}

// file: counter.harness.ts
import { BaseHarnessFilters, ComponentHarness, HarnessPredicate } from '@angular/cdk/testing';

export interface CounterHarnessFilters extends BaseHarnessFilters {
  minValue?: number;
}

export class CounterHarness extends ComponentHarness {
  static hostSelector = 'app-counter';

  private readonly value = this.locatorFor('[data-test="value"]');
  private readonly incButton = this.locatorFor('[data-test="inc"]');
  private readonly resetButton = this.locatorFor('[data-test="reset"]');

  static with(options: CounterHarnessFilters = {}): HarnessPredicate<CounterHarness> {
    return new HarnessPredicate(CounterHarness, options).addOption('minValue', options.minValue, async (harness, min) => {
      return (await harness.getValue()) >= min;
    });
  }

  async getValue(): Promise<number> {
    return Number(await (await this.value()).text());
  }

  async increment(): Promise<void> {
    await (await this.incButton()).click();
  }

  async reset(): Promise<void> {
    await (await this.resetButton()).click();
  }
}

// file: counter.component.spec.ts
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { Component } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { CounterComponent } from './counter.component';
import { CounterHarness } from './counter.harness';

@Component({
  selector: 'app-host',
  imports: [CounterComponent],
  template: `<app-counter /><app-counter />`,
})
class HostComponent {}

describe('CounterHarness', () => {
  let fixture: ComponentFixture<HostComponent>;

  beforeEach(() => {
    fixture = TestBed.createComponent(HostComponent);
  });

  it('increments and resets through the harness', async () => {
    const loader = TestbedHarnessEnvironment.loader(fixture);
    const counter = await loader.getHarness(CounterHarness);

    await counter.increment();
    await counter.increment();
    expect(await counter.getValue()).toBe(2);

    await counter.reset();
    expect(await counter.getValue()).toBe(0);
  });

  it('finds one of several counters with a predicate', async () => {
    const loader = TestbedHarnessEnvironment.loader(fixture);
    const [first] = await loader.getAllHarnesses(CounterHarness);
    await first.increment();

    const busy = await loader.getHarness(CounterHarness.with({ minValue: 1 }));
    expect(await busy.getValue()).toBe(1);
    expect((await loader.getAllHarnesses(CounterHarness)).length).toBe(2);
  });
});

Angular 20.3 with CDK 20.2. The spec was run in headless Chrome with `ng test`.

Key points

  • A harness hides DOM details behind a behaviour API, so refactors do not break tests.
  • Extend `ComponentHarness`, set `hostSelector`, use `locatorFor`, and return promises.
  • Auto-waits for stability. Use `TestbedHarnessEnvironment.loader(fixture)`.
  • Material ships harnesses. Use `documentRootLoader` for overlays.

Common mistakes

  • Forgetting to `await` harness calls, which makes assertions run too early.
  • Selecting by CSS classes used for styling inside the harness, instead of stable attributes such as `data-test`.
  • Writing a harness for a component that only one test uses.

Follow-ups

  • How do you find one of several harness instances with a predicate?
  • Where do the contents of a Material dialog live, and how do you test them?
  • When is querying the DOM directly still fine?

Tips

  • Show the before and after of one assertion. It makes the benefit clear.
  • Mention that Material and CDK ship harnesses for their own components.
  • Say that harness methods are async and auto-wait.

Evaluation rubric

  • Explains the problem harnesses solve.
  • Writes a harness with a host selector, locators, and methods.
  • Knows about predicates, overlays, and limits.