@react-aria/test-utils 1.0.0-alpha.1 → 1.0.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/combobox.main.js +137 -0
  2. package/dist/combobox.main.js.map +1 -0
  3. package/dist/combobox.mjs +132 -0
  4. package/dist/combobox.module.js +132 -0
  5. package/dist/combobox.module.js.map +1 -0
  6. package/dist/events.main.js +25 -10
  7. package/dist/events.main.js.map +1 -1
  8. package/dist/events.mjs +25 -10
  9. package/dist/events.module.js +25 -10
  10. package/dist/events.module.js.map +1 -1
  11. package/dist/gridlist.main.js +97 -0
  12. package/dist/gridlist.main.js.map +1 -0
  13. package/dist/gridlist.mjs +92 -0
  14. package/dist/gridlist.module.js +92 -0
  15. package/dist/gridlist.module.js.map +1 -0
  16. package/dist/import.mjs +4 -2
  17. package/dist/main.js +10 -18
  18. package/dist/main.js.map +1 -1
  19. package/dist/menu.main.js +220 -0
  20. package/dist/menu.main.js.map +1 -0
  21. package/dist/menu.mjs +215 -0
  22. package/dist/menu.module.js +215 -0
  23. package/dist/menu.module.js.map +1 -0
  24. package/dist/module.js +4 -2
  25. package/dist/module.js.map +1 -1
  26. package/dist/select.main.js +113 -0
  27. package/dist/select.main.js.map +1 -0
  28. package/dist/select.mjs +108 -0
  29. package/dist/select.module.js +108 -0
  30. package/dist/select.module.js.map +1 -0
  31. package/dist/table.main.js +187 -0
  32. package/dist/table.main.js.map +1 -0
  33. package/dist/table.mjs +182 -0
  34. package/dist/table.module.js +182 -0
  35. package/dist/table.module.js.map +1 -0
  36. package/dist/testSetup.main.js +2 -6
  37. package/dist/testSetup.main.js.map +1 -1
  38. package/dist/testSetup.mjs +2 -6
  39. package/dist/testSetup.module.js +2 -6
  40. package/dist/testSetup.module.js.map +1 -1
  41. package/dist/types.d.ts +186 -4
  42. package/dist/types.d.ts.map +1 -1
  43. package/dist/user.main.js +65 -0
  44. package/dist/user.main.js.map +1 -0
  45. package/dist/user.mjs +56 -0
  46. package/dist/user.module.js +56 -0
  47. package/dist/user.module.js.map +1 -0
  48. package/package.json +5 -5
  49. package/src/combobox.ts +188 -0
  50. package/src/events.ts +28 -8
  51. package/src/gridlist.ts +116 -0
  52. package/src/index.ts +6 -3
  53. package/src/menu.ts +308 -0
  54. package/src/select.ts +158 -0
  55. package/src/table.ts +273 -0
  56. package/src/testSetup.ts +2 -6
  57. package/src/user.ts +73 -0
package/src/table.ts ADDED
@@ -0,0 +1,273 @@
1
+ /*
2
+ * Copyright 2024 Adobe. All rights reserved.
3
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License. You may obtain a copy
5
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+ *
7
+ * Unless required by applicable law or agreed to in writing, software distributed under
8
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ * OF ANY KIND, either express or implied. See the License for the specific language
10
+ * governing permissions and limitations under the License.
11
+ */
12
+
13
+ import {act, fireEvent, waitFor, within} from '@testing-library/react';
14
+ import {BaseTesterOpts, UserOpts} from './user';
15
+ import {pressElement, triggerLongPress} from './events';
16
+ export interface TableOptions extends UserOpts, BaseTesterOpts {
17
+ user?: any,
18
+ advanceTimer: UserOpts['advanceTimer']
19
+ }
20
+
21
+ // TODO: Previously used logic like https://github.com/testing-library/react-testing-library/blame/c63b873072d62c858959c2a19e68f8e2cc0b11be/src/pure.js#L16
22
+ // but https://github.com/testing-library/dom-testing-library/issues/987#issuecomment-891901804 indicates that it may falsely indicate that fake timers are enabled
23
+ // when they aren't
24
+ export class TableTester {
25
+ private user;
26
+ private _interactionType: UserOpts['interactionType'];
27
+ private _advanceTimer: UserOpts['advanceTimer'];
28
+ private _table: HTMLElement;
29
+
30
+ constructor(opts: TableOptions) {
31
+ let {root, user, interactionType, advanceTimer} = opts;
32
+ this.user = user;
33
+ this._interactionType = interactionType || 'mouse';
34
+ this._advanceTimer = advanceTimer;
35
+ this._table = root;
36
+ }
37
+
38
+ setInteractionType = (type: UserOpts['interactionType']) => {
39
+ this._interactionType = type;
40
+ };
41
+
42
+ toggleRowSelection = async (opts: {index?: number, text?: string, needsLongPress?: boolean, interactionType?: UserOpts['interactionType']} = {}) => {
43
+ let {
44
+ index,
45
+ text,
46
+ needsLongPress,
47
+ interactionType = this._interactionType
48
+ } = opts;
49
+
50
+ let row = this.findRow({index, text});
51
+ let rowCheckbox = within(row).queryByRole('checkbox');
52
+ if (rowCheckbox) {
53
+ await pressElement(this.user, rowCheckbox, interactionType);
54
+ } else {
55
+ let cell = within(row).getAllByRole('gridcell')[0];
56
+ if (needsLongPress && interactionType === 'touch') {
57
+ if (this._advanceTimer == null) {
58
+ throw new Error('No advanceTimers provided for long press.');
59
+ }
60
+
61
+ // Note that long press interactions with rows is strictly touch only for grid rows
62
+ await triggerLongPress({element: cell, advanceTimer: this._advanceTimer, pointerOpts: {pointerType: 'touch'}});
63
+ // TODO: interestingly enough, we need to do a followup click otherwise future row selections may not fire properly?
64
+ // To reproduce, try removing this, forcing toggleRowSelection to hit "needsLongPress ? await triggerLongPress(cell) : await action(cell);" and
65
+ // run Table.test's "should support long press to enter selection mode on touch" test to see what happens
66
+ await fireEvent.click(cell);
67
+ } else {
68
+ await pressElement(this.user, cell, interactionType);
69
+ }
70
+ }
71
+ };
72
+
73
+ toggleSort = async (opts: {index?: number, text?: string, interactionType?: UserOpts['interactionType']} = {}) => {
74
+ let {
75
+ index,
76
+ text,
77
+ interactionType = this._interactionType
78
+ } = opts;
79
+
80
+ let columnheader;
81
+ if (index != null) {
82
+ columnheader = this.columns[index];
83
+ } else if (text != null) {
84
+ columnheader = within(this.rowGroups[0]).getByText(text);
85
+ while (columnheader && !/columnheader/.test(columnheader.getAttribute('role'))) {
86
+ columnheader = columnheader.parentElement;
87
+ }
88
+ }
89
+
90
+ let menuButton = within(columnheader).queryByRole('button');
91
+ if (menuButton) {
92
+ let currentSort = columnheader.getAttribute('aria-sort');
93
+ // TODO: Focus management is all kinda of messed up if I just use .focus and Space to open the sort menu. Seems like
94
+ // the focused key doesn't get properly set to the desired column header. Have to do this strange flow where I focus the
95
+ // column header except if the active element is already the menu button within the column header
96
+ if (interactionType === 'keyboard' && document.activeElement !== menuButton) {
97
+ await pressElement(this.user, columnheader, interactionType);
98
+ } else {
99
+ await pressElement(this.user, menuButton, interactionType);
100
+ }
101
+
102
+ await waitFor(() => {
103
+ if (menuButton.getAttribute('aria-controls') == null) {
104
+ throw new Error('No aria-controls found on table column dropdown menu trigger element.');
105
+ } else {
106
+ return true;
107
+ }
108
+ });
109
+
110
+ let menuId = menuButton.getAttribute('aria-controls');
111
+ await waitFor(() => {
112
+ if (!menuId || document.getElementById(menuId) == null) {
113
+ throw new Error(`Table column header menu with id of ${menuId} not found in document.`);
114
+ } else {
115
+ return true;
116
+ }
117
+ });
118
+
119
+ if (menuId) {
120
+ let menu = document.getElementById(menuId);
121
+ if (menu) {
122
+ if (currentSort === 'ascending') {
123
+ await pressElement(this.user, within(menu).getAllByRole('menuitem')[1], interactionType);
124
+ } else {
125
+ await pressElement(this.user, within(menu).getAllByRole('menuitem')[0], interactionType);
126
+ }
127
+
128
+ await waitFor(() => {
129
+ if (document.contains(menu)) {
130
+ throw new Error('Expected table column menu listbox to not be in the document after selecting an option');
131
+ } else {
132
+ return true;
133
+ }
134
+ });
135
+ }
136
+ }
137
+
138
+ // Handle cases where the table may transition in response to the row selection/deselection
139
+ if (!this._advanceTimer) {
140
+ throw new Error('No advanceTimers provided for table transition.');
141
+ }
142
+
143
+ await act(async () => {
144
+ await this._advanceTimer?.(200);
145
+ });
146
+
147
+ await waitFor(() => {
148
+ if (document.activeElement !== menuButton) {
149
+ throw new Error(`Expected the document.activeElement to be the table column menu button but got ${document.activeElement}`);
150
+ } else {
151
+ return true;
152
+ }
153
+ });
154
+ } else {
155
+ await pressElement(this.user, columnheader, interactionType);
156
+ }
157
+ };
158
+ // TODO: should there be a util for triggering a row action? Perhaps there should be but it would rely on the user teling us the config of the
159
+ // table. Maybe we could rely on the user knowing to trigger a press/double click? We could have the user pass in "needsDoubleClick"
160
+ // It is also iffy if there is any row selected because then the table is in selectionMode and the below actions will simply toggle row selection
161
+ triggerRowAction = async (opts: {index?: number, text?: string, needsDoubleClick?: boolean, interactionType?: UserOpts['interactionType']} = {}) => {
162
+ let {
163
+ index,
164
+ text,
165
+ needsDoubleClick,
166
+ interactionType = this._interactionType
167
+ } = opts;
168
+
169
+ let row = this.findRow({index, text});
170
+ if (row) {
171
+ if (needsDoubleClick) {
172
+ await this.user.dblClick(row);
173
+ } else if (interactionType === 'keyboard') {
174
+ act(() => row.focus());
175
+ await this.user.keyboard('[Enter]');
176
+ } else {
177
+ await pressElement(this.user, row, interactionType);
178
+ }
179
+ }
180
+ };
181
+
182
+ // TODO: should there be utils for drag and drop and column resizing? For column resizing, I'm not entirely convinced that users will be doing that in their tests.
183
+ // For DnD, it might be tricky to do for keyboard DnD since we wouldn't know what valid drop zones there are... Similarly, for simulating mouse drag and drop the coordinates depend
184
+ // on the mocks the user sets up for their row height/etc.
185
+ // Additionally, should we also support keyboard navigation/typeahead? Those felt like they could be very easily replicated by the user via user.keyboard already and don't really
186
+ // add much value if we provide that to them
187
+
188
+ toggleSelectAll = async (opts: {interactionType?: UserOpts['interactionType']} = {}) => {
189
+ let {
190
+ interactionType = this._interactionType
191
+ } = opts;
192
+ let checkbox = within(this.table).getByLabelText('Select All');
193
+ if (interactionType === 'keyboard') {
194
+ // TODO: using the .focus -> trigger keyboard Enter approach doesn't work for some reason, for now just trigger select all with click.
195
+ await this.user.click(checkbox);
196
+ } else {
197
+ await pressElement(this.user, checkbox, interactionType);
198
+ }
199
+ };
200
+
201
+ findRow = (opts: {index?: number, text?: string} = {}) => {
202
+ let {
203
+ index,
204
+ text
205
+ } = opts;
206
+
207
+ let row;
208
+ let rows = this.rows;
209
+ let bodyRowGroup = this.rowGroups[1];
210
+ if (index != null) {
211
+ row = rows[index];
212
+ } else if (text != null) {
213
+ row = within(bodyRowGroup).getByText(text);
214
+ while (row && row.getAttribute('role') !== 'row') {
215
+ row = row.parentElement;
216
+ }
217
+ }
218
+
219
+ return row;
220
+ };
221
+
222
+ findCell = (opts: {text: string}) => {
223
+ let {
224
+ text
225
+ } = opts;
226
+
227
+ let cell = within(this.table).getByText(text);
228
+ if (cell) {
229
+ while (cell && !/gridcell|rowheader|columnheader/.test(cell.getAttribute('role') || '')) {
230
+ if (cell.parentElement) {
231
+ cell = cell.parentElement;
232
+ } else {
233
+ break;
234
+ }
235
+ }
236
+ }
237
+
238
+ return cell;
239
+ };
240
+
241
+ get table() {
242
+ return this._table;
243
+ }
244
+
245
+ get rowGroups() {
246
+ let table = this._table;
247
+ return table ? within(table).queryAllByRole('rowgroup') : [];
248
+ }
249
+
250
+ get columns() {
251
+ let headerRowGroup = this.rowGroups[0];
252
+ return headerRowGroup ? within(headerRowGroup).queryAllByRole('columnheader') : [];
253
+ }
254
+
255
+ get rows() {
256
+ let bodyRowGroup = this.rowGroups[1];
257
+ return bodyRowGroup ? within(bodyRowGroup).queryAllByRole('row') : [];
258
+ }
259
+
260
+ get selectedRows() {
261
+ return this.rows.filter(row => row.getAttribute('aria-selected') === 'true');
262
+ }
263
+
264
+ get rowHeaders() {
265
+ let table = this.table;
266
+ return table ? within(table).queryAllByRole('rowheader') : [];
267
+ }
268
+
269
+ get cells() {
270
+ let table = this.table;
271
+ return table ? within(table).queryAllByRole('gridcell') : [];
272
+ }
273
+ }
package/src/testSetup.ts CHANGED
@@ -14,9 +14,8 @@
14
14
  * Enables reading pageX/pageY from fireEvent.mouse*(..., {pageX: ..., pageY: ...}).
15
15
  */
16
16
  export function installMouseEvent() {
17
+ let oldMouseEvent = MouseEvent;
17
18
  beforeAll(() => {
18
- let oldMouseEvent = MouseEvent;
19
- // @ts-ignore
20
19
  global.MouseEvent = class FakeMouseEvent extends MouseEvent {
21
20
  _init: {pageX: number, pageY: number};
22
21
  constructor(name, init) {
@@ -30,12 +29,9 @@ export function installMouseEvent() {
30
29
  return this._init.pageY;
31
30
  }
32
31
  };
33
- // @ts-ignore
34
- global.MouseEvent.oldMouseEvent = oldMouseEvent;
35
32
  });
36
33
  afterAll(() => {
37
- // @ts-ignore
38
- global.MouseEvent = global.MouseEvent.oldMouseEvent;
34
+ global.MouseEvent = oldMouseEvent;
39
35
  });
40
36
  }
41
37
 
package/src/user.ts ADDED
@@ -0,0 +1,73 @@
1
+ /*
2
+ * Copyright 2024 Adobe. All rights reserved.
3
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License. You may obtain a copy
5
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+ *
7
+ * Unless required by applicable law or agreed to in writing, software distributed under
8
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ * OF ANY KIND, either express or implied. See the License for the specific language
10
+ * governing permissions and limitations under the License.
11
+ */
12
+
13
+ import {ComboBoxOptions, ComboBoxTester} from './combobox';
14
+ import {GridListOptions, GridListTester} from './gridlist';
15
+ import {MenuOptions, MenuTester} from './menu';
16
+ import {pointerMap} from './';
17
+ import {SelectOptions, SelectTester} from './select';
18
+ import {TableOptions, TableTester} from './table';
19
+ import userEvent from '@testing-library/user-event';
20
+
21
+ // https://github.com/testing-library/dom-testing-library/issues/939#issuecomment-830771708 is an interesting way of allowing users to configure the timers
22
+ // curent way is like https://testing-library.com/docs/user-event/options/#advancetimers,
23
+ export interface UserOpts {
24
+ interactionType?: 'mouse' | 'touch' | 'keyboard',
25
+ // If using fake timers user should provide something like (time) => jest.advanceTimersByTime(time))}
26
+ // A real timer user would pass async () => await new Promise((resolve) => setTimeout(resolve, waitTime))
27
+ // Time is in ms.
28
+ advanceTimer?: (time?: number) => void | Promise<unknown>
29
+ }
30
+
31
+ export interface BaseTesterOpts {
32
+ // The base element for the given tester (e.g. the table, menu trigger, etc)
33
+ root: HTMLElement
34
+ }
35
+
36
+ let keyToUtil = {'Select': SelectTester, 'Table': TableTester, 'Menu': MenuTester, 'ComboBox': ComboBoxTester, 'GridList': GridListTester} as const;
37
+ export type PatternNames = keyof typeof keyToUtil;
38
+
39
+ // Conditional type: https://www.typescriptlang.org/docs/handbook/2/conditional-types.html
40
+ type ObjectType<T> =
41
+ T extends 'Select' ? SelectTester :
42
+ T extends 'Table' ? TableTester :
43
+ T extends 'Menu' ? MenuTester :
44
+ T extends 'ComboBox' ? ComboBoxTester :
45
+ T extends 'GridList' ? GridListTester :
46
+ never;
47
+
48
+ type ObjectOptionsTypes<T> =
49
+ T extends 'Select' ? SelectOptions :
50
+ T extends 'Table' ? TableOptions :
51
+ T extends 'Menu' ? MenuOptions :
52
+ T extends 'ComboBox' ? ComboBoxOptions :
53
+ T extends 'GridList' ? GridListOptions :
54
+ never;
55
+
56
+ let defaultAdvanceTimer = async (waitTime: number | undefined) => await new Promise((resolve) => setTimeout(resolve, waitTime));
57
+
58
+ export class User {
59
+ user;
60
+ interactionType: UserOpts['interactionType'];
61
+ advanceTimer: UserOpts['advanceTimer'];
62
+
63
+ constructor(opts: UserOpts = {}) {
64
+ let {interactionType, advanceTimer} = opts;
65
+ this.user = userEvent.setup({delay: null, pointerMap});
66
+ this.interactionType = interactionType;
67
+ this.advanceTimer = advanceTimer || defaultAdvanceTimer;
68
+ }
69
+
70
+ createTester<T extends PatternNames>(patternName: T, opts: ObjectOptionsTypes<T>): ObjectType<T> {
71
+ return new (keyToUtil)[patternName]({user: this.user, interactionType: this.interactionType, advanceTimer: this.advanceTimer, ...opts}) as ObjectType<T>;
72
+ }
73
+ }