-
Notifications
You must be signed in to change notification settings - Fork 1.3k
feat: Add CheckBoxGroup/Dialog/RadioGroup test utils #9039
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
54e54a2
f1058b2
72da10f
5955a51
b87cdac
e556c9c
5cf5388
e828412
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,158 @@ | ||
/* | ||
* Copyright 2025 Adobe. All rights reserved. | ||
* This file is licensed to you under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. You may obtain a copy | ||
* of the License at http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software distributed under | ||
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS | ||
* OF ANY KIND, either express or implied. See the License for the specific language | ||
* governing permissions and limitations under the License. | ||
*/ | ||
|
||
import {act, within} from '@testing-library/react'; | ||
import {CheckboxGroupTesterOpts, UserOpts} from './types'; | ||
import {pressElement} from './events'; | ||
|
||
interface TriggerCheckboxOptions { | ||
/** | ||
* What interaction type to use when triggering a checkbox. Defaults to the interaction type set on the tester. | ||
*/ | ||
interactionType?: UserOpts['interactionType'], | ||
/** | ||
* The index, text, or node of the checkbox to toggle selection for. | ||
*/ | ||
checkbox: number | string | HTMLElement | ||
} | ||
|
||
export class CheckboxGroupTester { | ||
private user; | ||
private _interactionType: UserOpts['interactionType']; | ||
private _checkboxgroup: HTMLElement; | ||
|
||
|
||
constructor(opts: CheckboxGroupTesterOpts) { | ||
let {root, user, interactionType} = opts; | ||
this.user = user; | ||
this._interactionType = interactionType || 'mouse'; | ||
|
||
this._checkboxgroup = root; | ||
let checkboxgroup = within(root).queryAllByRole('group'); | ||
if (checkboxgroup.length > 0) { | ||
this._checkboxgroup = checkboxgroup[0]; | ||
} | ||
} | ||
|
||
/** | ||
* Set the interaction type used by the checkbox group tester. | ||
*/ | ||
setInteractionType(type: UserOpts['interactionType']): void { | ||
this._interactionType = type; | ||
} | ||
|
||
/** | ||
* Returns a checkbox matching the specified index or text content. | ||
*/ | ||
findCheckbox(opts: {checkboxIndexOrText: number | string}): HTMLElement { | ||
let { | ||
checkboxIndexOrText | ||
} = opts; | ||
|
||
let checkbox; | ||
if (typeof checkboxIndexOrText === 'number') { | ||
checkbox = this.checkboxes[checkboxIndexOrText]; | ||
} else if (typeof checkboxIndexOrText === 'string') { | ||
let label = within(this.checkboxgroup).getByText(checkboxIndexOrText); | ||
|
||
// Label may wrap the checkbox, or the actual label may be a sibling span, or the checkbox div could have the label within it | ||
if (label) { | ||
checkbox = within(label).queryByRole('checkbox'); | ||
if (!checkbox) { | ||
let labelWrapper = label.closest('label'); | ||
if (labelWrapper) { | ||
checkbox = within(labelWrapper).queryByRole('checkbox'); | ||
} else { | ||
checkbox = label.closest('[role=checkbox]'); | ||
} | ||
} | ||
} | ||
} | ||
|
||
return checkbox; | ||
} | ||
|
||
private async keyboardNavigateToCheckbox(opts: {checkbox: HTMLElement}) { | ||
let {checkbox} = opts; | ||
let checkboxes = this.checkboxes; | ||
checkboxes = checkboxes.filter(checkbox => !(checkbox.hasAttribute('disabled') || checkbox.getAttribute('aria-disabled') === 'true')); | ||
if (checkboxes.length === 0) { | ||
throw new Error('Checkbox group doesnt have any non-disabled checkboxes. Please double check your checkbox group.'); | ||
} | ||
|
||
let targetIndex = checkboxes.indexOf(checkbox); | ||
if (targetIndex === -1) { | ||
throw new Error('Checkbox provided is not in the checkbox group.'); | ||
} | ||
|
||
if (!this.checkboxgroup.contains(document.activeElement)) { | ||
act(() => checkboxes[0].focus()); | ||
} | ||
|
||
let currIndex = checkboxes.indexOf(document.activeElement as HTMLElement); | ||
if (currIndex === -1) { | ||
throw new Error('Active element is not in the checkbox group.'); | ||
} | ||
|
||
for (let i = 0; i < Math.abs(targetIndex - currIndex); i++) { | ||
await this.user.tab({shift: targetIndex < currIndex}); | ||
} | ||
}; | ||
|
||
/** | ||
* Toggles the specified checkbox. Defaults to using the interaction type set on the checkbox tester. | ||
*/ | ||
async toggleCheckbox(opts: TriggerCheckboxOptions): Promise<void> { | ||
let { | ||
checkbox, | ||
interactionType = this._interactionType | ||
} = opts; | ||
|
||
if (typeof checkbox === 'string' || typeof checkbox === 'number') { | ||
checkbox = this.findCheckbox({checkboxIndexOrText: checkbox}); | ||
} | ||
|
||
if (!checkbox) { | ||
throw new Error('Target checkbox not found in the checkboxgroup.'); | ||
} else if (checkbox.hasAttribute('disabled')) { | ||
throw new Error('Target checkbox is disabled.'); | ||
} | ||
|
||
if (interactionType === 'keyboard') { | ||
await this.keyboardNavigateToCheckbox({checkbox}); | ||
await this.user.keyboard('[Space]'); | ||
} else { | ||
await pressElement(this.user, checkbox, interactionType); | ||
} | ||
} | ||
|
||
/** | ||
* Returns the checkboxgroup. | ||
*/ | ||
get checkboxgroup(): HTMLElement { | ||
return this._checkboxgroup; | ||
} | ||
|
||
/** | ||
* Returns the checkboxes. | ||
*/ | ||
get checkboxes(): HTMLElement[] { | ||
return within(this.checkboxgroup).queryAllByRole('checkbox'); | ||
} | ||
|
||
/** | ||
* Returns the currently selected checkboxes in the checkboxgroup if any. | ||
*/ | ||
get selectedCheckboxes(): HTMLElement[] { | ||
return this.checkboxes.filter(checkbox => (checkbox as HTMLInputElement).checked || checkbox.getAttribute('aria-checked') === 'true'); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,147 @@ | ||||||
/* | ||||||
* Copyright 2025 Adobe. All rights reserved. | ||||||
* This file is licensed to you under the Apache License, Version 2.0 (the "License"); | ||||||
* you may not use this file except in compliance with the License. You may obtain a copy | ||||||
* of the License at http://www.apache.org/licenses/LICENSE-2.0 | ||||||
* | ||||||
* Unless required by applicable law or agreed to in writing, software distributed under | ||||||
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS | ||||||
* OF ANY KIND, either express or implied. See the License for the specific language | ||||||
* governing permissions and limitations under the License. | ||||||
*/ | ||||||
|
||||||
import {act, waitFor, within} from '@testing-library/react'; | ||||||
import {DialogTesterOpts, UserOpts} from './types'; | ||||||
|
||||||
interface DialogOpenOpts { | ||||||
/** | ||||||
* What interaction type to use when opening the dialog. Defaults to the interaction type set on the tester. | ||||||
*/ | ||||||
interactionType?: UserOpts['interactionType'] | ||||||
} | ||||||
|
||||||
export class DialogTester { | ||||||
private user; | ||||||
private _interactionType: UserOpts['interactionType']; | ||||||
private _trigger: HTMLElement | undefined; | ||||||
private _dialog: HTMLElement | undefined; | ||||||
// TODO: may not need this? Isn't really useful | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. dialog vs alertdialog? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. right, but functionally they don't behave any differently so the only place it gets used here is for assertion of existence which is fine I guess. Mainly thinking that people writing tests at an app level may not care/know what kind of dialog is being opened and instead just need to know that a dialog opened. |
||||||
private _dialogType: DialogTesterOpts['dialogType']; | ||||||
private _overlayType: DialogTesterOpts['overlayType']; | ||||||
|
||||||
constructor(opts: DialogTesterOpts) { | ||||||
let {root, user, interactionType, dialogType, overlayType} = opts; | ||||||
this.user = user; | ||||||
this._interactionType = interactionType || 'mouse'; | ||||||
this._dialogType = dialogType || 'dialog'; | ||||||
this._overlayType = overlayType || 'modal'; | ||||||
|
||||||
// Handle case where element provided is a wrapper of the trigger button | ||||||
let trigger = within(root).queryByRole('button'); | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. && aria-expanded is an attribute on the button? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. for buttons that open a modal type dialog, they don't get |
||||||
if (trigger) { | ||||||
this._trigger = trigger; | ||||||
} else { | ||||||
this._trigger = root; | ||||||
} | ||||||
} | ||||||
|
||||||
/** | ||||||
* Set the interaction type used by the dialog tester. | ||||||
*/ | ||||||
setInteractionType(type: UserOpts['interactionType']): void { | ||||||
this._interactionType = type; | ||||||
} | ||||||
|
||||||
/** | ||||||
* Opens the dialog. Defaults to using the interaction type set on the dialog tester. | ||||||
*/ | ||||||
async open(opts: DialogOpenOpts = {}): Promise<void> { | ||||||
let { | ||||||
interactionType = this._interactionType | ||||||
} = opts; | ||||||
let trigger = this.trigger; | ||||||
if (!trigger.hasAttribute('disabled')) { | ||||||
if (interactionType === 'mouse') { | ||||||
await this.user.click(trigger); | ||||||
} else if (interactionType === 'touch') { | ||||||
await this.user.pointer({target: trigger, keys: '[TouchA]'}); | ||||||
} else if (interactionType === 'keyboard') { | ||||||
act(() => trigger.focus()); | ||||||
await this.user.keyboard('[Enter]'); | ||||||
} | ||||||
|
||||||
if (this._overlayType === 'popover') { | ||||||
await waitFor(() => { | ||||||
if (trigger.getAttribute('aria-controls') == null) { | ||||||
throw new Error('No aria-controls found on dialog trigger element.'); | ||||||
} else { | ||||||
return true; | ||||||
} | ||||||
}); | ||||||
|
||||||
let dialogId = trigger.getAttribute('aria-controls'); | ||||||
await waitFor(() => { | ||||||
if (!dialogId || document.getElementById(dialogId) == null) { | ||||||
throw new Error(`Dialog with id of ${dialogId} not found in document.`); | ||||||
} else { | ||||||
this._dialog = document.getElementById(dialogId)!; | ||||||
return true; | ||||||
} | ||||||
}); | ||||||
} else { | ||||||
let dialog; | ||||||
await waitFor(() => { | ||||||
dialog = document.querySelector(`[role=${this._dialogType}]`); | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. could just use
Suggested change
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this util won't work for nested dialogs, maybe query all and filter out inert ones? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. yep, this was the reason for me wondering if |
||||||
if (dialog == null) { | ||||||
throw new Error(`No dialog of type ${this._dialogType} found after pressing the trigger.`); | ||||||
} else { | ||||||
return true; | ||||||
} | ||||||
}); | ||||||
|
||||||
if (dialog && document.activeElement !== this._trigger && dialog.contains(document.activeElement)) { | ||||||
this._dialog = dialog; | ||||||
} else { | ||||||
// TODO: is it too brittle to throw here? | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. seems fine? were you running into unexpected cases? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. mainly still unsure if timing might throw off this check, but seems ok so far |
||||||
throw new Error('New modal dialog doesnt contain the active element OR the active element is still the trigger. Uncertain if the proper modal dialog was found'); | ||||||
} | ||||||
} | ||||||
} | ||||||
} | ||||||
|
||||||
/** | ||||||
* Closes the dialog via the Escape key. | ||||||
*/ | ||||||
async close(): Promise<void> { | ||||||
let dialog = this._dialog; | ||||||
if (dialog) { | ||||||
await this.user.keyboard('[Escape]'); | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. only for isKeyboardDismissable? maybe close could take an argument to a button to click for that modality? also, there's the hidden dismiss buttons for popovers if modality is virtual There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I opted to start with simplicity first, especially since dialog content is so custom that the user is probably already querying for buttons that can close the dialog and thus can simply trigger a press themselves. If they aren't querying for a specific close button already, then they probably aren't testing that My current philosophy for the test utils is that they should be used alongside your standard user events and element queries rather than be a wholesale replacement. Therefore, if the util doesn't cut down on the number of lines you write or help query for elements in a way that it also is asserting for roles/state then it doesn't need to handle it. |
||||||
await waitFor(() => { | ||||||
if (document.contains(dialog)) { | ||||||
throw new Error('Expected the dialog to not be in the document after closing it.'); | ||||||
} else { | ||||||
this._dialog = undefined; | ||||||
return true; | ||||||
} | ||||||
}); | ||||||
} | ||||||
} | ||||||
|
||||||
/** | ||||||
* Returns the dialog's trigger. | ||||||
*/ | ||||||
get trigger(): HTMLElement { | ||||||
if (!this._trigger) { | ||||||
throw new Error('No trigger element found for dialog.'); | ||||||
} | ||||||
|
||||||
return this._trigger; | ||||||
} | ||||||
|
||||||
/** | ||||||
* Returns the dialog if present. | ||||||
*/ | ||||||
get dialog(): HTMLElement | null { | ||||||
return this._dialog && document.contains(this._dialog) ? this._dialog : null; | ||||||
} | ||||||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should we do this by default? It can sometimes cause behaviour that doesn't match real life. Maybe there should be an option to force focus, but otherwise we throw if they aren't in the checkbox group already?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
From feedback for other users and my own experience from converting tests in Quarry to use the test utils, there is often a lot of friction when people are integrating the utils into the flow of their existing test and expect that calling these "toggle/trigger" functions should just work, even if active focus is in a separate place in their app and the real life use case would be to press Tab 4x to get to the checkboxgroup/etc. I think ideally everyones tests would simulate the exact user flows but realistically I'd like there to be as little friction as possible in adoption.