Skip to content

Commit 4f0878f

Browse files
committed
feat: use a11y queries in selectOptions
1 parent 7f39bf4 commit 4f0878f

File tree

1 file changed

+14
-16
lines changed

1 file changed

+14
-16
lines changed

projects/testing-library/src/lib/user-events/selectOptions.ts

+14-16
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,4 @@
1-
import {
2-
FireFunction,
3-
FireObject,
4-
Matcher,
5-
getByText,
6-
SelectorMatcherOptions,
7-
queryByText,
8-
} from '@testing-library/dom';
1+
import { FireFunction, FireObject, Matcher, screen, ByRoleOptions } from '@testing-library/dom';
92

103
// implementation from https://github.com/testing-library/user-event
114
export function createSelectOptions(fireEvent: FireFunction & FireObject) {
@@ -18,10 +11,16 @@ export function createSelectOptions(fireEvent: FireFunction & FireObject) {
1811
fireEvent.click(element);
1912
}
2013

21-
function selectOption(select: HTMLSelectElement, index: number, matcher: Matcher, options?: SelectorMatcherOptions) {
22-
// fallback to document.body, because libraries as Angular Material will have their custom select component
23-
const option = (queryByText(select, matcher, options) ||
24-
getByText(document.body, matcher, options)) as HTMLOptionElement;
14+
function selectOption(select: HTMLSelectElement, index: number, options: Matcher | ByRoleOptions) {
15+
const query =
16+
typeof options === 'string'
17+
? (({ name: new RegExp(options, 'i') } as unknown) as ByRoleOptions)
18+
: options instanceof RegExp
19+
? (({ name: options } as unknown) as ByRoleOptions)
20+
: typeof options === 'function'
21+
? (({ name: options } as unknown) as ByRoleOptions)
22+
: options;
23+
const option = screen.getByRole('option', query) as HTMLOptionElement;
2524

2625
fireEvent.mouseOver(option);
2726
fireEvent.mouseMove(option);
@@ -36,8 +35,7 @@ export function createSelectOptions(fireEvent: FireFunction & FireObject) {
3635

3736
return async function selectOptions(
3837
element: HTMLElement,
39-
matcher: Matcher | Matcher[],
40-
matcherOptions?: SelectorMatcherOptions,
38+
options: Matcher | ByRoleOptions | ((Matcher | ByRoleOptions)[]),
4139
) {
4240
const selectElement = element as HTMLSelectElement;
4341

@@ -55,10 +53,10 @@ export function createSelectOptions(fireEvent: FireFunction & FireObject) {
5553

5654
clickElement(selectElement);
5755

58-
const values = Array.isArray(matcher) ? matcher : [matcher];
56+
const values = Array.isArray(options) ? options : [options];
5957
values
6058
.filter((_, index) => index === 0 || selectElement.multiple)
61-
.forEach((val, index) => selectOption(selectElement, index, val, matcherOptions));
59+
.forEach((val, index) => selectOption(selectElement, index, val));
6260

6361
if (wasAnotherElementFocused) {
6462
fireEvent.blur(focusedElement);

0 commit comments

Comments
 (0)