skip to content

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%

answer

  1. a testing entry point per component
  2. static with() builds the filter
  3. every call returns a Promise
  4. no detectChanges between steps
  5. string text filter matches exactly

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.

solid answer

~40 s

Each Material component that has a harness ships it in a separate `testing` entry point beside it, so `@angular/material/button/testing` exports `MatButtonHarness` and its `ButtonHarnessFilters`. In the test I get a loader for the fixture from the CDK's testing package, ask it for `MatButtonHarness.with({text: 'Save'})`, and call `await save.click()`. Every harness method returns a Promise, and the harness runs change detection and waits for the fixture to settle around each call, so I don't sprinkle `fixture.detectChanges()` between steps. Afterwards I can read what a user sees: `isDisabled()`, `getText()`, `isFocused()`. One trap: a string `text` filter must equal the button's trimmed text exactly, so for a button with an icon or extra words I pass a RegExp.

code

ts · 27 lines
ts
import {TestBed} from '@angular/core/testing';
import {HarnessLoader} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {MatButtonHarness} from '@angular/material/button/testing';
import {RecipeEditor} from './recipe-editor';
import {RecipeStore} from './recipe-store';

describe('RecipeEditor', () => {
  let loader: HarnessLoader;

  beforeEach(() => {
    const fixture = TestBed.createComponent(RecipeEditor);
    loader = TestbedHarnessEnvironment.loader(fixture);
  });

  it('saves the recipe', async () => {
    const store = TestBed.inject(RecipeStore);
    spyOn(store, 'save');

    const save = await loader.getHarness(MatButtonHarness.with({text: 'Save'}));
    expect(await save.isDisabled()).toBe(false);
    expect(await save.getAppearance()).toBe('filled');

    await save.click();
    expect(store.save).toHaveBeenCalled();
  });
});

go deeper

for a junior

Recall the testing entry point beside each component, the with() filter, and that every harness call must be awaited.

for a middle

Explain why no detectChanges calls are needed and how the text filter matches, including the exact-match trap with icons.

for a senior

Show how you pick buttons by meaning rather than index so a growing form does not break dozens of tests.

for a principal

Weigh standardising on Material's harnesses across a suite against the cost of migrating tests when filters change between majors.

## Where the ready-made harnesses live Angular Material publishes a **component test harness** for most of its components: a class that lets a test click, type into and read a component through a typed API instead of through its internal DOM. Each one lives in a **secondary entry point named `testing`** next to the component it drives, so test-only code never mixes with what the application imports. | Component | Runtime import | Harness import | Harness class | |---|---|---|---| | Button | `@angular/material/button` | `@angular/material/button/testing` | `MatButtonHarness` | | Input | `@angular/material/input` | `@angular/material/input/testing` | `MatInputHarness` | | Select | `@angular/material/select` | `@angular/material/select/testing` | `MatSelectHarness` | | Dialog | `@angular/material/dialog` | `@angular/material/dialog/testing` | `MatDialogHarness` | | Table | `@angular/material/table` | `@angular/material/table/testing` | `MatTableHarness` | The harness base classes and the loaders that find harnesses come from the CDK's testing package (`@angular/cdk/testing` and `@angular/cdk/testing/testbed`). How that machinery works is a separate subject; for Material's ready-made classes you only need one fact: a **loader** rooted at your component fixture can hand you a harness instance. ## Clicking the Save button In a recipe-sharing app, the recipe editor has a filled **Save** button written as `<button matButton="filled">Save</button>`. A test that clicks it through the harness takes four steps: 1. Create the component fixture and a loader for it. 2. Ask the loader for `MatButtonHarness.with({text: 'Save'})`, which returns the first button whose text is exactly `Save`. 3. `await save.click()`. 4. Assert the outcome: a service call, an emitted value, or the button's new state. There is no `fixture.detectChanges()` and no `whenStable()` between the steps. The harness environment runs change detection after every action and before every read, and waits for the fixture to be stable, so the test reads like a script of user actions. ## What the button harness can read and do `MatButtonHarness` exposes actions a user could take and state a user could perceive: - `click()`, optionally at a relative position or at `'center'` - `focus()`, `blur()` and `isFocused()` - `getText()`, the button's trimmed text content - `isDisabled()`, true for the `disabled` attribute or the disabled class Material adds - `getVariant()`, one of `basic`, `icon`, `fab` or `mini-fab` - `getAppearance()`, one of `text`, `filled`, `elevated`, `outlined` or `tonal` - `getType()`, the `type` attribute when it is `button`, `submit` or `reset` - `isShowingProgress()`, whether a progress indicator is projected into the button ## Why isDisabled() beats reading the DOM property A Save button that is disabled until the recipe has a title can be written with `disabledInteractive`, so it stays focusable and can show a tooltip explaining why it is off. In that mode Material leaves out the native `disabled` attribute, sets `aria-disabled="true"`, and adds its own disabled class. A raw test that checks `button.disabled` reads `false` and concludes the button is enabled. `MatButtonHarness.isDisabled()` checks both the attribute and Material's disabled class, so it reports `true` in either mode, which is what a user would perceive. ## Filters that pick one button `MatButtonHarness.with(filters)` narrows the search. Besides the `selector` and `ancestor` options every Material harness accepts, the button adds its own: | Filter | Matches | |---|---| | `text` | trimmed text content, exact for a string, tested for a RegExp | | `variant` | `basic`, `icon`, `fab` or `mini-fab` | | `appearance` | `text`, `filled`, `elevated`, `outlined` or `tonal` | | `disabled` | the disabled state | | `buttonType` | the `type` attribute | | `iconName` | a projected `mat-icon` with that name | Two version notes matter on Material 22. In version 20 the appearance moved out of `getVariant()` into its own `getAppearance()` method and `appearance` filter, so older tests that expected `getVariant()` to report the look of the button, such as `flat` or `stroked`, need rewriting. The `iconName` filter arrived in version 21. ## Common slips - **Forgetting `await`.** Every harness method returns a Promise; an un-awaited `click()` lets the assertion run first. - **Picking by index.** `getAllHarnesses(MatButtonHarness)` followed by `[2]` breaks when someone adds a button; a `text` or `selector` filter does not. - **Exact text with an icon inside.** A ligature icon such as `<mat-icon>save</mat-icon>` puts its name into the button's text content, so a string filter of `Save` no longer matches. Use a RegExp such as `/Save$/`, or `iconName` with a `selector`. - **Importing the harness from the CDK.** `@angular/cdk/testing` holds the base API, not `MatButtonHarness`.

  • The Save button contains a save icon before its label. How do you still find it with MatButtonHarness?
    The ligature text `save` is part of the button's text content, so `{text: 'Save'}` fails the exact match. Pass a RegExp, `MatButtonHarness.with({text: /Save$/})`, or narrow by icon with `{iconName: 'save'}` together with a `selector`. Since version 21 the `iconName` filter looks for a projected `mat-icon` with that name.
  • An older test asserts that getVariant() returns 'flat'. Why does it fail on Material 22, and what replaces it?
    Since version 20 `getVariant()` reports only the structural kind, `basic`, `icon`, `fab` or `mini-fab`. The look moved to `getAppearance()`, which returns `text`, `filled`, `elevated`, `outlined` or `tonal`, and to a matching `appearance` filter. A flat button is now the `filled` appearance.

  • Material's harness classes are imported from @angular/cdk/testing.
  • You must call fixture.detectChanges() after every harness click.
  • A string text filter matches any button whose label contains it.
  • getVariant() tells you whether a button is filled or outlined.
  • Harness methods are synchronous, so await is optional.

Assumes Angular Material 22; getAppearance() and the appearance filter split from getVariant() in 20, and the iconName filter arrived in 21.