skip to content

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%

answer

  1. open() before reading options
  2. options scoped to its own panel
  3. first match versus every match
  4. a selected option toggles off
  5. no match throws

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.

solid answer

~40 s

`MatSelectHarness.open()` clicks the trigger unless the panel is already open, and `getOptions({text, isSelected})` returns `MatOptionHarness` instances from that select's own panel only. `getOptions()` does not open anything, so on a closed select it returns an empty array. `clickOptions(filter)` opens the panel first, throws if no option matches, clicks just the first match on a single select and every match on a multiple select. Because clicking a selected option in multiple mode deselects it, I add `isSelected: false` to the filter when I mean "make sure these are on". Then `getValueText()` gives me what the trigger displays. The harness searches from the document root, so it works whether the panel renders inline as a popover or in the overlay container.

code

ts · 20 lines
ts
import {MatSelectHarness} from '@angular/material/select/testing';

it('filters by diet and allergens', async () => {
  const diet = await loader.getHarness(MatSelectHarness.with({label: 'Diet'}));
  expect(await diet.getOptions()).toEqual([]); // panel not rendered yet

  await diet.open();
  const options = await diet.getOptions();
  const labels = await Promise.all(options.map(o => o.getText()));
  expect(labels).toEqual(['Any', 'Vegetarian', 'Vegan']);

  await diet.clickOptions({text: 'Vegan'});
  expect(await diet.getValueText()).toBe('Vegan');

  const allergens = await loader.getHarness(
    MatSelectHarness.with({label: 'Allergens to avoid'}),
  );
  // Nuts may already be selected from the saved profile: only click options still off.
  await allergens.clickOptions({text: /^(Nuts|Dairy)$/, isSelected: false});
});

go deeper

for a junior

Recall open(), getOptions() and clickOptions(), and that getOptions() needs the panel open.

for a middle

Explain how clickOptions differs between single and multiple mode and what the option filter matches.

for a senior

Diagnose a flaky multi-select test caused by toggling a pre-selected option, and explain why panel location never matters to the harness.

for a principal

Decide whether shared test helpers should wrap clickOptions with an isSelected guard, trading convenience against hiding the toggle semantics.

## The scenario The recipe search form has a single-selection `mat-select` labelled **Diet** (Any, Vegetarian, Vegan) and a multiple-selection one labelled **Allergens to avoid** (Nuts, Dairy, Gluten, Shellfish). Tests need to read the options, pick one diet, and switch several allergens on without accidentally switching others off. ## The methods that drive the panel | Method | What it does | |---|---| | `open()` | Clicks the trigger, but only when the panel is not already open | | `isOpen()` | Whether this select's panel is in the document | | `getOptions(filter?)` | `MatOptionHarness[]` from this select's panel; does **not** open it | | `getOptionGroups(filter?)` | `MatOptgroupHarness[]` from the same panel | | `clickOptions(filter?)` | Opens the panel, then clicks matching options | | `getValueText()` | The text the trigger currently displays | | `close()` | Clicks the overlay backdrop if the panel is open | The option filter, from `@angular/material/core/testing`, accepts `text` (a string for an exact match on the trimmed text, or a RegExp) and `isSelected`, plus the usual `selector`. `MatOptionHarness` itself offers `click()`, `getText()`, `isSelected()`, `isDisabled()` and `isActive()`. ## How clickOptions decides what to click Read from the source, `clickOptions(filter)` runs these steps: 1. Call `open()`, so the test never has to. 2. Ask whether the select is multiple and collect the matching options, in parallel. 3. If no option matches, **throw** `Select does not have options matching the specified filter`. 4. On a **multiple** select, click every matching option. 5. On a **single** select, click only the **first** matching option. Two consequences follow: - **A broad RegExp on a single select is quietly narrowed.** `clickOptions({text: /Veg/})` matches Vegetarian and Vegan and clicks Vegetarian, the first one. Prefer an exact string when the choice matters. - **A multiple select toggles.** Clicking an option that is already selected deselects it. If Nuts is pre-selected from a saved profile, `clickOptions({text: /Nuts|Dairy/})` turns Nuts **off** and Dairy on. Adding `isSelected: false` to the filter clicks only the ones that are still off. ## Why the panel's location never reaches your test The harness locates its options through a document-root locator, scoped to the panel whose id is the select's id followed by `-panel`. Two things make that matter in Material 22: - **The panel's location varies.** The select now 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 through the overlay's default configuration or are unavailable. Searching from the root works in every case. - **Two selects on one page do not mix.** Because the search is scoped to this select's panel id, the Diet harness never returns the Allergens options, even if both panels were open. The scoping also explains the common surprise: `getOptions()` on a closed select returns `[]`, because the panel is only rendered while the select is open. ## When the test needs one option's state Sometimes the test is about a single option rather than the selection, for example that **Vegan** is disabled while an "Includes meat" toggle on the form is on. Open the select and ask for that option directly: - `const [vegan] = await diet.getOptions({text: 'Vegan'})`, then `await vegan.isDisabled()`; - `await diet.getOptions({isSelected: true})` lists the options currently chosen, which on a multiple select is a cleaner assertion than parsing the trigger text; - `await vegan.isActive()` reports the keyboard-highlighted option after arrow-key navigation. Option groups work the same way: `getOptionGroups({labelText: 'Asian'})` returns the matching group harnesses, so options grouped by cuisine can be read group by group. ## Reading the result After picking, assert what the user sees, not the component's private state: - `getValueText()` returns the trigger text, such as `Vegan` or, for a multiple select, the comma-joined selection Material displays. - `isEmpty()` tells you nothing is selected, and `isMultiple()` confirms the mode. - For the panel itself, `isOpen()` reports whether it is still rendered. Note that `close()` works by clicking the overlay backdrop and assumes only one overlay is open at a time; for most tests, letting a single selection close the panel, or pressing on with the next action, is simpler.

  • A test calls clickOptions({text: 'Vegan '}) with a trailing space. What happens?
    The option harness compares a string filter against the option's trimmed text with strict equality, so `'Vegan '` matches nothing. `clickOptions` then throws `Select does not have options matching the specified filter` rather than silently doing nothing, which makes the typo visible in the test output.
  • How do you check that the Diet select is marked invalid after the user leaves it empty?
    `MatSelectHarness.isValid()` returns false when the host carries Angular's `ng-invalid` class, and `isRequired()` reports the required state. When and how the form field shows its error message is the form field's concern, so for the message itself you read the surrounding form field rather than the select.

  • getOptions() opens the select panel for you.
  • clickOptions on a single select clicks every matching option.
  • clickOptions silently does nothing when no option matches.
  • Clicking an already-selected option in a multiple select keeps it selected.
  • MatSelectHarness.close() presses Escape on the select.

Assumes Angular Material 22, where mat-select renders its panel as a native popover placed inline after its form field by default; the harness's document-root search covers that and the overlay container alike.