Skip to content
Open
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
158 changes: 158 additions & 0 deletions packages/@react-aria/test-utils/src/checkboxgroup.ts
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');
}
}
147 changes: 147 additions & 0 deletions packages/@react-aria/test-utils/src/dialog.ts
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
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');
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}]`);
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?
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]');
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;
}
}
Loading