skip to content

Ready-Made Test Harnesses

Each Material component ships a test harness, such as MatButtonHarness or MatSelectHarness, so a test clicks, reads and filters it through a typed API. Interviewers ask what it saves over raw DOM.

part ofAngular Material & CDKread it →
on this pageshow

explore

questions

5

Testing a recipe search form, what do Angular Material's MatInputHarness and MatSelectHarness spare you compared with querying the components' DOM directly?

level: middleimportance: must knowfreq 35%

answer

  1. internal classes are not your API
  2. events and timing handled for you
  3. find controls by their label
  4. panel location stops mattering
  5. maintained with the component

basics

~20 s

They hide Material's internal DOM, fire the right events, wait for the fixture to settle, and find controls by label. When a Material release restructures a component, its harness changes in the same release, sparing your tests.

solid answer

~40 s

A raw test has to know Material's internals: the `.mat-mdc-select-trigger` element to click, where the option panel is rendered, which events to dispatch on the input, and when to call `detectChanges()` and `whenStable()`. `MatInputHarness.setValue()` clears the field, types the text key by key and sets the value, and `MatSelectHarness.clickOptions({text: 'Vegan'})` opens the panel and clicks the option wherever it is rendered. Both find a control by its form-field label, `with({label: 'Diet'})`, and read state such as `getValue()`, `getValueText()` or `isRequired()`. Because the Angular team updates the harness whenever the component's DOM changes, an upgrade that renames classes or moves the panel doesn't break tests that go through the harness.

code

ts · 15 lines
ts
it('searches vegan lentil recipes (raw DOM)', async () => {
  const input: HTMLInputElement = fixture.nativeElement.querySelector('input');
  input.value = 'lentil';
  input.dispatchEvent(new Event('input'));
  fixture.detectChanges();

  fixture.nativeElement.querySelector('.mat-mdc-select-trigger').click();
  fixture.detectChanges();
  await fixture.whenStable();

  const options = document.querySelectorAll('.mat-mdc-option');
  (options[2] as HTMLElement).click(); // third option, hopefully "Vegan"
  fixture.detectChanges();
  await fixture.whenStable();
});

go deeper

for a junior

Recall that Material ships input and select harnesses with setValue, clickOptions and a label filter.

for a middle

Explain the three things they absorb: internal DOM, event and timing choreography, and where the option panel is rendered.

for a senior

Argue for harnesses in a suite that must survive Material upgrades, and name what they still leave coupled.

for a principal

Weigh a suite-wide rule to drive every Material control through its harness against the cost of retrofitting existing raw tests.

## The scenario A recipe-sharing app has a search form: a text input labelled **Search recipes** inside a `mat-form-field`, and a `mat-select` labelled **Diet** with the options Any, Vegetarian and Vegan. The test types `lentil`, picks Vegan, and checks that the search request carries both. ## What a raw DOM test has to know Written against the DOM, the test encodes facts that belong to Angular Material, not to your app: 1. **Internal class names.** To open the select you click the trigger element, whose class is an internal detail. When Material moved to its MDC-based components, `.mat-select-trigger` became `.mat-mdc-select-trigger`, and every test that queried the old name broke without any change in what users saw. 2. **Where the option panel lives.** In Material 22 the select renders its panel as a native popover placed inline, right after the form field it is anchored to, when the browser supports popovers, and in the CDK overlay container on `document.body` when popovers are switched off or unavailable. A raw query has to guess which. 3. **Event choreography.** Typing means setting `value`, dispatching an `input` event, then running change detection. Leave out a step and the form control never hears about it. 4. **Timing.** Opening a select and clicking an option involve asynchronous work, so raw tests accumulate `detectChanges()`, `whenStable()` and sometimes `tick()` calls, and those change when a component's internals switch between synchronous and asynchronous. ## What the two harnesses do instead | Job | Raw DOM test | Material harness | |---|---|---| | Find the field | `querySelector('input')` or an index | `MatInputHarness.with({label: 'Search recipes'})` | | Type text | set `value`, dispatch `input`, detect changes | `await search.setValue('lentil')` | | Open the select | click `.mat-mdc-select-trigger` | `await diet.open()` or let `clickOptions` do it | | Pick an option | query option elements, click by index | `await diet.clickOptions({text: 'Vegan'})` | | Read the choice | read the trigger's inner text | `await diet.getValueText()` | | Wait for the UI | `detectChanges()` and `whenStable()` | automatic before reads and after actions | Some details worth knowing: - **`setValue()`** clears the input, types the new text key by key (firing keyboard and `input` events), then sets the `value` property, so both template-driven and reactive forms see the change. - **The `label` filter**, shared by every form-field control harness, resolves the label the way assistive technology does: through the control's `aria-labelledby`, then its `aria-label`, then a `<label for>` that points at it. - **`MatInputHarness` filters** also include `value` and `placeholder`; it reads `getValue()`, `getName()`, `getType()`, `isRequired()`, `isReadonly()` and `isDisabled()`. - **`MatSelectHarness`** reads `getValueText()`, `isEmpty()`, `isMultiple()`, `isRequired()` and `isValid()`, and searches for its options from the document root, scoped to its own panel, so the location question from step 2 disappears. ## Reading state as a user would The harnesses also answer questions a raw test answers awkwardly. After the user clears the search box, `await search.getValue()` returns `''`; after a reset, `await diet.isEmpty()` returns `true`; when the form marks the select as required, `await diet.isRequired()` reflects it. Each read runs change detection first, so the answer matches what is on screen at that moment rather than what was there before the last action. For the question of which control is focused after a keyboard step, both harnesses offer `isFocused()`, `focus()` and `blur()`. ## Why the robustness is real, not cosmetic The harness is part of Angular Material and ships in the same release as the component. When a fix restructures the select's DOM or changes its timing, the maintainers update `MatSelectHarness` in the same change and every consumer's tests keep working. The using-harnesses guide in the components repository names two primary benefits: tests that are easier to read, and tests that are less likely to break when Angular Material is updated. ## What the harnesses do not do - They cover **Material's components only**. Your own recipe-card component needs a harness you write with the CDK's testing API, or a different style of query. - They do not decide **what to assert**. A test that drives the select through its harness and then inspects your component's private fields is still coupled to internals. - They make the test **slightly more verbose** in `async` and `await`, because every call returns a Promise.

  • How does the label filter on MatInputHarness or MatSelectHarness find the label text?
    Both inherit it from Material's form-field control harness base. It follows the control's `aria-labelledby` to the element with that id and reads its text; if there is none it uses `aria-label`; failing that it looks for a `<label for>` pointing at the control's id. A `mat-label` inside `mat-form-field` is wired through `aria-labelledby`, so `with({label: 'Diet'})` just works.
  • Why does MatInputHarness.setValue() both type keys and set the value property?
    Typing key by key fires the keyboard and `input` events a forms binding or a key handler listens to. Some input types, such as `color`, ignore key presses, so the harness then sets the `value` property as well to guarantee the final value. It sets it after typing, not before, so the text is not entered twice.
  • Does a Material harness make a test behaviour-focused on its own?
    No. It only removes coupling to Material's internals. If the test then asserts on your component's private state or on markup you own, it is still brittle at that layer; the harness covers the Material controls, and you still choose assertions a user would recognise.

  • Harnesses query the same internal classes, so they break just as often.
  • MatInputHarness.setValue() writes straight into the FormControl, skipping DOM events.
  • You still need fixture.whenStable() after each harness call.
  • Angular Material ships harnesses for your own app components too.
  • Harnesses only work in end-to-end tests, not in TestBed unit tests.
open as a page

In an Angular Material 22 test, where do you import MatButtonHarness from, and how do you click the recipe form's Save button through it?

level: juniorimportance: should knowfreq 30%

basics

~10 s

Import it from the button's own testing entry point, @angular/material/button/testing, load it with MatButtonHarness.with({text: 'Save'}), then await its click(). Harness calls are asynchronous and run change detection themselves.

open as a page

Testing a delete-recipe confirmation opened with Angular Material's MatDialog, what can MatDialogHarness check and do, and how do you test the dialog component on its own?

level: seniorimportance: should knowfreq 22%

basics

~20 s

MatDialogHarness, loaded from the document root, reads the title, content and actions text plus role and ARIA attributes, finds buttons inside the dialog, and closes it by pressing Escape. MatTestDialogOpener opens the dialog component alone and records its result.

open as a page

With Angular Material's MatSelectHarness, how do you open the diet select and pick options, and how does clickOptions behave in single versus multiple mode?

level: seniorimportance: should knowfreq 24%

basics

~20 s

Call open() and getOptions() to read the options, or clickOptions(filter), which opens the panel itself. On a single select it clicks the first match; on a multiple select it clicks every match, and it throws when nothing matches.

open as a page

How do you assert the rows of an Angular Material results table with MatTableHarness, and what do its cell-text methods return?

level: seniorimportance: nice to knowfreq 18%

basics

~10 s

MatTableHarness gives row and cell harnesses plus two shortcuts: getCellTextByIndex() returns a string grid of the data rows, and getCellTextByColumnName() returns, per column, the data, header and footer texts.

open as a page