Skip to content

Commit ac7df56

Browse files
committed
feat(material/autocomplete): test harness should throw when options are requested but panel is closed
The autocomplete harness has methods for retrieving the options of an autocomplete. When this method is invoked, the options are determined from the overlay DOM element, if available. If the panel is not in the DOM (due to the autocomplete not being focused), the method will just return an empty array, indicating that there are no options. This is confusing for test authors and currently not well-defined, potentially causing invalid tests that just pass by coincidence. We want to throw when the panel is not open, raising awareness for such invalid tests. In the future we may want to auto-focus the autocomplete to open the panel (like `selectOption`).
1 parent 0f8d529 commit ac7df56

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

src/material/autocomplete/testing/autocomplete-harness.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
ComponentHarness,
1313
ComponentHarnessConstructor,
1414
HarnessPredicate,
15+
TestElement,
1516
} from '@angular/cdk/testing';
1617
import {
1718
MatOptgroupHarness,
@@ -71,6 +72,10 @@ export abstract class _MatAutocompleteHarnessBase<
7172

7273
/** Gets the options inside the autocomplete panel. */
7374
async getOptions(filters?: Omit<OptionFilters, 'ancestor'>): Promise<Option[]> {
75+
if (!(await this.isOpen())) {
76+
throw new Error('Unable to retrieve options for autocomplete. Autocomplete panel is closed.');
77+
}
78+
7479
return this._documentRootLocator.locatorForAll(
7580
this._optionClass.with({
7681
...(filters || {}),
@@ -81,6 +86,12 @@ export abstract class _MatAutocompleteHarnessBase<
8186

8287
/** Gets the option groups inside the autocomplete panel. */
8388
async getOptionGroups(filters?: Omit<OptionGroupFilters, 'ancestor'>): Promise<OptionGroup[]> {
89+
if (!(await this.isOpen())) {
90+
throw new Error(
91+
'Unable to retrieve option groups for autocomplete. Autocomplete panel is closed.',
92+
);
93+
}
94+
8495
return this._documentRootLocator.locatorForAll(
8596
this._optionGroupClass.with({
8697
...(filters || {}),
@@ -106,7 +117,7 @@ export abstract class _MatAutocompleteHarnessBase<
106117
}
107118

108119
/** Gets the panel associated with this autocomplete trigger. */
109-
private async _getPanel() {
120+
private async _getPanel(): Promise<TestElement | null> {
110121
// Technically this is static, but it needs to be in a
111122
// function, because the autocomplete's panel ID can changed.
112123
return this._documentRootLocator.locatorForOptional(await this._getPanelSelector())();

0 commit comments

Comments
 (0)