-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSelectNext-test.js
515 lines (436 loc) · 14.9 KB
/
SelectNext-test.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
import { checkAccessibility, waitFor } from '@hypothesis/frontend-testing';
import { mount } from 'enzyme';
import { MultiSelect, Select, SelectNext } from '../Select';
describe('Select', () => {
let wrappers;
const items = [
{ id: '1', name: 'All students' },
{ id: '2', name: 'Albert Banana' },
{ id: '3', name: 'Bernard California' },
{ id: '4', name: 'Cecelia Davenport' },
{ id: '5', name: 'Doris Evanescence' },
];
/**
* @param {Object} [options]
* @param {number} [options.paddingTop] - Extra padding top for the container.
* Defaults to 0.
* @param {boolean} [options.optionsChildrenAsCallback] -
* Whether to render Select.Option children with callback notation.
* Used primarily to test and cover both branches.
* Defaults to true.
* @param {MultiSelect | Select | SelectNext} [options.Component] -
* The actual "select" component to use. Defaults to `Select`.
*/
const createComponent = (props = {}, options = {}) => {
const {
paddingTop = 0,
optionsChildrenAsCallback = true,
Component = Select,
} = options;
const container = document.createElement('div');
container.style.paddingTop = `${paddingTop}px`;
document.body.append(container);
const wrapper = mount(
<Component value={undefined} onChange={sinon.stub()} {...props}>
<Component.Option value={undefined}>
<span data-testid="reset-option">Reset</span>
</Component.Option>
{items.map(item => (
<Component.Option
value={item}
disabled={item.id === '4'}
key={item.id}
>
{!optionsChildrenAsCallback ? (
<span data-testid={`option-${item.id}`}>{item.name}</span>
) : (
({ selected, disabled }) => (
<span data-testid={`option-${item.id}`}>
{item.name}
{selected && <span data-testid="selected-option" />}
{disabled && <span data-testid="disabled-option" />}
</span>
)
)}
</Component.Option>
))}
</Component>,
{ attachTo: container },
);
wrappers.push(wrapper);
return wrapper;
};
beforeEach(() => {
wrappers = [];
});
afterEach(() => {
wrappers.forEach(wrapper => wrapper.unmount());
});
const getToggleButton = wrapper =>
wrapper.find('button[data-testid="select-toggle-button"]');
const toggleListbox = wrapper => getToggleButton(wrapper).simulate('click');
const getListbox = wrapper => wrapper.find('[data-testid="select-listbox"]');
const isListboxClosed = wrapper =>
getListbox(wrapper).prop('data-listbox-open') === false;
const listboxDidDropUp = wrapper => {
const { top: listboxTop } = getListbox(wrapper)
.getDOMNode()
.getBoundingClientRect();
const { top: buttonTop } = getToggleButton(wrapper)
.getDOMNode()
.getBoundingClientRect();
return listboxTop < buttonTop;
};
const clickOption = (wrapper, id) =>
wrapper.find(`[data-testid="option-${id}"]`).simulate('click');
it('changes selected value when an option is clicked', () => {
const onChange = sinon.stub();
const wrapper = createComponent({ onChange });
clickOption(wrapper, 3);
assert.calledWith(onChange.lastCall, items[2]);
clickOption(wrapper, 5);
assert.calledWith(onChange.lastCall, items[4]);
clickOption(wrapper, 1);
assert.calledWith(onChange.lastCall, items[0]);
});
it('does not change selected value when a disabled option is clicked', () => {
const onChange = sinon.stub();
const wrapper = createComponent({ onChange });
const clickDisabledOption = () =>
wrapper.find(`[data-testid="option-4"]`).simulate('click');
clickDisabledOption();
assert.notCalled(onChange);
});
['Enter', 'Space'].forEach(code => {
it(`changes selected value when ${code} is pressed in option`, () => {
const onChange = sinon.stub();
const wrapper = createComponent({ onChange });
const pressKeyInOption = index =>
wrapper
.find(`[data-testid="option-${index}"]`)
.getDOMNode()
.closest('[role="option"]')
.dispatchEvent(new KeyboardEvent('keypress', { code }));
pressKeyInOption(3);
assert.calledWith(onChange.lastCall, items[2]);
pressKeyInOption(5);
assert.calledWith(onChange.lastCall, items[4]);
pressKeyInOption(1);
assert.calledWith(onChange.lastCall, items[0]);
});
it(`does not change selected value when ${code} is pressed in a disabled option`, () => {
const onChange = sinon.stub();
const wrapper = createComponent({ onChange });
const pressKeyInDisabledOption = () =>
wrapper
.find(`[data-testid="option-4"]`)
.getDOMNode()
.closest('[role="option"]')
.dispatchEvent(new KeyboardEvent('keypress', { code }));
pressKeyInDisabledOption();
assert.notCalled(onChange);
});
});
it('marks the right item as selected', () => {
const wrapper = createComponent({ value: items[2] });
const isOptionSelected = id =>
wrapper
.find(`[data-testid="option-${id}"]`)
.exists('[data-testid="selected-option"]');
assert.isFalse(isOptionSelected(1));
assert.isFalse(isOptionSelected(2));
assert.isTrue(isOptionSelected(3));
assert.isFalse(isOptionSelected(4));
assert.isFalse(isOptionSelected(5));
});
it('marks the right item as disabled', () => {
const wrapper = createComponent();
const isOptionDisabled = id =>
wrapper
.find(`[data-testid="option-${id}"]`)
.exists('[data-testid="disabled-option"]');
assert.isFalse(isOptionDisabled(1));
assert.isFalse(isOptionDisabled(2));
assert.isFalse(isOptionDisabled(3));
assert.isTrue(isOptionDisabled(4));
assert.isFalse(isOptionDisabled(5));
});
it('toggles listbox when button is clicked', () => {
const wrapper = createComponent();
assert.isTrue(isListboxClosed(wrapper));
toggleListbox(wrapper);
assert.isFalse(isListboxClosed(wrapper));
});
it('closes listbox when Escape is pressed', () => {
const wrapper = createComponent();
toggleListbox(wrapper);
assert.isFalse(isListboxClosed(wrapper));
document.body.dispatchEvent(
new KeyboardEvent('keydown', { key: 'Escape' }),
);
wrapper.update();
// Listbox is closed after `Escape` is pressed
assert.isTrue(isListboxClosed(wrapper));
});
it('closes listbox when clicking away', () => {
const wrapper = createComponent();
toggleListbox(wrapper);
assert.isFalse(isListboxClosed(wrapper));
const externalButton = document.createElement('button');
document.body.append(externalButton);
externalButton.click();
wrapper.update();
try {
// Listbox is closed after other element is clicked
assert.isTrue(isListboxClosed(wrapper));
} finally {
externalButton.remove();
}
});
it('closes listbox when focusing away', () => {
const wrapper = createComponent();
toggleListbox(wrapper);
// Focus an element which is outside the listbox itself
const outerButton = document.createElement('button');
document.body.append(outerButton);
outerButton.focus();
wrapper.update();
try {
assert.isTrue(isListboxClosed(wrapper));
// The button should still be focused after closing the listbox
assert.equal(document.activeElement, outerButton);
} finally {
outerButton.remove();
}
});
it('restores focus to toggle button after closing listbox', () => {
const wrapper = createComponent();
toggleListbox(wrapper);
// Focus listbox option before closing listbox
wrapper
.find('[data-testid="option-3"]')
.getDOMNode()
.closest('[role="option"]')
.focus();
toggleListbox(wrapper);
wrapper.update();
assert.equal(document.activeElement, getToggleButton(wrapper).getDOMNode());
});
it('displays listbox when ArrowDown is pressed on toggle', () => {
const wrapper = createComponent();
assert.isTrue(isListboxClosed(wrapper));
getToggleButton(wrapper)
.getDOMNode()
.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown' }));
wrapper.update();
assert.isFalse(isListboxClosed(wrapper));
});
[
{
containerPaddingTop: 0,
shouldDropUp: false,
listboxAsPopover: undefined,
},
{
containerPaddingTop: 0,
shouldDropUp: false,
listboxAsPopover: true,
},
{
containerPaddingTop: 0,
shouldDropUp: false,
listboxAsPopover: false,
},
{
containerPaddingTop: 1000,
shouldDropUp: true,
listboxAsPopover: undefined,
},
{
containerPaddingTop: 1000,
shouldDropUp: true,
listboxAsPopover: true,
},
{
containerPaddingTop: 1000,
shouldDropUp: true,
listboxAsPopover: false,
},
].forEach(({ containerPaddingTop, shouldDropUp, listboxAsPopover }) => {
it('makes listbox drop up or down based on available space below', () => {
const wrapper = createComponent(
{ listboxAsPopover },
{ paddingTop: containerPaddingTop },
);
toggleListbox(wrapper);
assert.equal(listboxDidDropUp(wrapper), shouldDropUp);
});
});
context('when Option is rendered outside of Select', () => {
it('throws an error', () => {
assert.throws(
() => mount(<Select.Option value="1">{() => '1'}</Select.Option>),
'Select.Option can only be used as Select or MultiSelect child',
);
});
});
context('when popover is supported', () => {
[undefined, true].forEach(listboxAsPopover => {
it('opens listbox via popover API', async () => {
const wrapper = createComponent({ listboxAsPopover });
let resolve;
const promise = new Promise(res => (resolve = res));
getListbox(wrapper).getDOMNode().addEventListener('toggle', resolve);
toggleListbox(wrapper);
// This test will timeout if the toggle event is not dispatched
await promise;
});
});
});
context('when listbox is bigger than toggle button', () => {
[
// Inferring listboxAsPopover based on browser support
{
listboxAsPopover: undefined,
getListboxLeft: wrapper => {
const leftStyle = getListbox(wrapper).getDOMNode().style.left;
// Remove `px` unit indicator
return Number(leftStyle.replace('px', ''));
},
},
// Explicitly enabling listboxAsPopover
{
listboxAsPopover: true,
getListboxLeft: wrapper => {
const leftStyle = getListbox(wrapper).getDOMNode().style.left;
// Remove `px` unit indicator
return Number(leftStyle.replace('px', ''));
},
},
// Explicitly disabling listboxAsPopover
{
listboxAsPopover: false,
getListboxLeft: wrapper =>
getListbox(wrapper).getDOMNode().getBoundingClientRect().left,
},
].forEach(({ listboxAsPopover, getListboxLeft }) => {
it('aligns listbox to the right if `right` prop is true', async () => {
const wrapper = createComponent({
listboxAsPopover,
right: true,
buttonClasses: '!w-8', // Set a small width in the button
});
toggleListbox(wrapper);
// Wait for listbox to be open
await waitFor(() => !isListboxClosed(wrapper));
const { left: buttonLeft } = getToggleButton(wrapper)
.getDOMNode()
.getBoundingClientRect();
const listboxLeft = getListboxLeft(wrapper);
assert.isTrue(listboxLeft < buttonLeft);
});
});
});
context('SelectNext', () => {
// This path can only be tested via SelectNext
it('throws if multiple is true and the value is not an array', async () => {
assert.throws(
() => createComponent({ multiple: true }, { Component: SelectNext }),
'When `multiple` is true, the value must be an array',
);
});
});
context('MultiSelect', () => {
it('keeps listbox open when an option is selected if multiple is true', async () => {
const wrapper = createComponent(
{ value: [] },
{ Component: MultiSelect },
);
toggleListbox(wrapper);
assert.isFalse(isListboxClosed(wrapper));
clickOption(wrapper, 1);
// After clicking an option, the listbox is still open
assert.isFalse(isListboxClosed(wrapper));
});
it('allows multiple items to be selected', () => {
const onChange = sinon.stub();
const wrapper = createComponent(
{
value: [items[0], items[2]],
onChange,
},
{ Component: MultiSelect },
);
toggleListbox(wrapper);
clickOption(wrapper, 2);
// When a not-yet-selected item is clicked, it will be selected
assert.calledWith(onChange, [items[0], items[2], items[1]]);
});
it('allows deselecting already selected options', () => {
const onChange = sinon.stub();
const wrapper = createComponent(
{
value: [items[0], items[2]],
onChange,
},
{ Component: MultiSelect },
);
toggleListbox(wrapper);
clickOption(wrapper, 3);
// When an already selected item is clicked, it will be de-selected
assert.calledWith(onChange, [items[0]]);
});
it('resets selection when option value is nullish and select value is an array', () => {
const onChange = sinon.stub();
const wrapper = createComponent(
{
value: [items[0], items[2]],
onChange,
},
{ Component: MultiSelect },
);
toggleListbox(wrapper);
wrapper.find(`[data-testid="reset-option"]`).simulate('click');
assert.calledWith(onChange, []);
});
});
it(
'should pass a11y checks',
checkAccessibility([
{
name: 'Closed Select listbox',
content: () =>
createComponent(
{ buttonContent: 'Select', 'aria-label': 'Select' },
{ optionsChildrenAsCallback: false },
),
},
{
name: 'Open Select listbox',
content: () => {
const wrapper = createComponent(
{ buttonContent: 'Select', 'aria-label': 'Select' },
{ optionsChildrenAsCallback: false },
);
toggleListbox(wrapper);
return wrapper;
},
},
{
name: 'Open MultiSelect listbox',
content: () => {
const wrapper = createComponent(
{
buttonContent: 'Select',
'aria-label': 'Select',
value: [items[1], items[3]],
},
{ optionsChildrenAsCallback: false, Component: MultiSelect },
);
toggleListbox(wrapper);
return wrapper;
},
},
]),
);
});