-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathAutocomplete.test.tsx
More file actions
1042 lines (861 loc) · 30 KB
/
Copy pathAutocomplete.test.tsx
File metadata and controls
1042 lines (861 loc) · 30 KB
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import { useState } from 'react'
import {
render,
fireEvent,
screen,
within,
waitFor,
} from '@testing-library/react'
import '@testing-library/jest-dom'
import styled from 'styled-components'
import { Autocomplete } from '.'
import { EdsProvider } from '../EdsProvider'
const itemObjects = [{ label: 'One' }, { label: 'Two' }, { label: 'Three' }]
const items = ['One', 'Two', 'Three']
const labelText = 'Select label test'
const mockResizeObserver = jest.fn(() => ({
observe: jest.fn(),
disconnect: jest.fn(),
unobserve: jest.fn(),
}))
jest.mock('@tanstack/react-virtual', () => ({
useVirtualizer: jest.fn((options) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const count = options?.count || 3
const items = Array.from({ length: count }, (_, index) => ({
index,
start: index * 48,
size: 48,
key: index,
}))
return {
getVirtualItems: () => items,
getTotalSize: () => count * 48,
scrollToIndex: jest.fn(),
measureElement: jest.fn(),
measure: jest.fn(),
}
}),
}))
beforeAll(() => {
window.ResizeObserver = mockResizeObserver
//https://github.com/TanStack/virtual/issues/641
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
Element.prototype.getBoundingClientRect = jest.fn(() => {
return {
width: 120,
height: 120,
top: 0,
left: 0,
bottom: 0,
right: 0,
}
})
})
const waitForVirtualizedOptions = async (
optionsList: HTMLElement,
expectedCount: number,
) => {
await waitFor(
() => {
const options = within(optionsList).queryAllByRole('option')
expect(options.length).toBeGreaterThanOrEqual(expectedCount)
},
{ timeout: 3000 },
)
const options = within(optionsList).getAllByRole('option')
const validOptions = options.filter((option) => {
const text = option.textContent?.trim()
return text && text.length > 0
})
return validOptions.slice(0, expectedCount)
}
const StyledAutocomplete = styled(Autocomplete)`
clip-path: unset;
`
describe('Autocomplete', () => {
it('Matches snapshot', async () => {
const { container } = render(
<Autocomplete options={items} label={labelText} />,
)
const autocomplete = screen.getAllByLabelText(labelText)
const input = autocomplete[0]
fireEvent.click(input)
const openAutocomplete = await screen.findAllByLabelText(labelText)
const optionsList = openAutocomplete[1]
await waitFor(() => {
expect(optionsList).toBeInTheDocument()
})
// Replace auto-generated IDs with static values for deterministic snapshots
const htmlString = container.innerHTML
const normalizedHtml = htmlString
.replace(/id="downshift-[^"]*"/g, 'id="downshift-test-id"')
.replace(
/aria-labelledby="downshift-[^"]*"/g,
'aria-labelledby="downshift-test-label-id"',
)
.replace(
/aria-controls="downshift-[^"]*"/g,
'aria-controls="downshift-test-controls"',
)
.replace(/for="downshift-[^"]*"/g, 'for="downshift-test-id"')
expect(normalizedHtml).toMatchSnapshot()
})
it('Has provided label', async () => {
render(<Autocomplete label={labelText} options={items} />)
// The same label is used for both the input field and the list of options
const labeledNodes = await screen.findAllByLabelText(labelText)
const input = labeledNodes[0]
const optionsList = labeledNodes[1]
expect(input).toBeDefined()
expect(input).toHaveAccessibleName(labelText)
expect(input.nodeName).toBe('INPUT')
expect(optionsList).toBeDefined()
expect(optionsList).toHaveAccessibleName(labelText)
expect(optionsList.nodeName).toBe('UL')
})
it('Preserves user-provided id on the input element', () => {
render(<Autocomplete id="my-custom-id" label={labelText} options={items} />)
const input = screen.getAllByLabelText(labelText)[0]
expect(input).toHaveAttribute('id', 'my-custom-id')
})
it('Maintains label-input association when custom id is provided', () => {
render(<Autocomplete id="my-custom-id" label={labelText} options={items} />)
// getByRole finds the input via its associated label, confirming the for/id link works
expect(screen.getByRole('combobox', { name: labelText })).toHaveAttribute(
'id',
'my-custom-id',
)
})
it('Has provided ReactNode label', async () => {
render(<Autocomplete label={<div>{labelText}</div>} options={items} />)
// The same label is used for both the input field and the list of options
const labeledNodes = await screen.findAllByLabelText(labelText)
const input = labeledNodes[0]
const optionsList = labeledNodes[1]
expect(input).toBeDefined()
expect(input).toHaveAccessibleName(labelText)
expect(input.nodeName).toBe('INPUT')
expect(optionsList).toBeDefined()
expect(optionsList).toHaveAccessibleName(labelText)
expect(optionsList.nodeName).toBe('UL')
})
it('Has provided option label', async () => {
const labler = (text: string) => `${text}+1`
render(
<Autocomplete
options={itemObjects}
label={labelText}
optionLabel={(item) => labler(item.label)}
/>,
)
const labeledNodes = await screen.findAllByLabelText(labelText)
const optionsList = labeledNodes[1]
const buttonNode = await screen.findByLabelText('toggle options', {
selector: 'button',
})
expect(optionsList.childNodes).toHaveLength(0)
fireEvent.click(buttonNode)
const options = await waitForVirtualizedOptions(optionsList, 3)
expect(
within(options[0]).getByText(labler(itemObjects[0].label)),
).toBeDefined()
expect(
within(options[1]).getByText(labler(itemObjects[1].label)),
).toBeDefined()
expect(
within(options[2]).getByText(labler(itemObjects[2].label)),
).toBeDefined()
})
it('Can render custom items with optionComponent', async () => {
type Item = {
label: string
}
function CustomItem(option: Item) {
const { label } = option
return <h1>{label}</h1>
}
render(
<Autocomplete
options={itemObjects}
label={labelText}
optionLabel={(item) => item.label}
optionComponent={CustomItem}
/>,
)
const labeledNodes = await screen.findAllByLabelText(labelText)
const optionsList = labeledNodes[1]
const buttonNode = await screen.findByLabelText('toggle options', {
selector: 'button',
})
expect(optionsList.childNodes).toHaveLength(0)
fireEvent.click(buttonNode)
const options = await waitForVirtualizedOptions(optionsList, 3)
expect(within(options[0]).getByText(itemObjects[0].label)).toBeDefined()
const heading = screen.getByText(itemObjects[0].label)
expect(heading.nodeName).toBe('H1')
})
it('Can be disabled', async () => {
render(<Autocomplete label={labelText} options={items} disabled />)
const labeledNodes = await screen.findAllByLabelText(labelText)
const input = labeledNodes[0]
expect(input).toBeDisabled()
})
it('Can preselect specific options', async () => {
render(
<Autocomplete
options={items}
label={labelText}
initialSelectedOptions={['One', 'Two']}
multiple
/>,
)
const input = await screen.findByPlaceholderText('2/3 selected')
fireEvent.click(input)
await waitFor(() => {
const checkboxes = screen.queryAllByRole('checkbox')
expect(checkboxes.length).toBeGreaterThan(0)
})
const checkboxes = await screen.findAllByRole('checkbox')
const checked = checkboxes.filter((x) => x.hasAttribute('checked'))
expect(input).toBeDefined()
expect(checked.length).toBe(2)
})
it('Can select all options', async () => {
const onChange = jest.fn()
render(
<StyledAutocomplete
//a bug in styled-components 6.1.8 breaks the conditional type for optionLabel when using styled(Autocomplete)
optionLabel={(option: unknown) => option as string}
label={labelText}
options={items}
data-testid="styled-autocomplete"
multiple={true}
allowSelectAll={true}
onOptionsChange={onChange}
/>,
)
const labeledNodes = await screen.findAllByLabelText(labelText)
const optionsList = labeledNodes[1]
const buttonNode = await screen.findByLabelText('toggle options', {
selector: 'button',
})
fireEvent.click(buttonNode)
await waitFor(() => {
const options = within(optionsList).queryAllByRole('option')
expect(options.length).toBeGreaterThanOrEqual(3)
})
const options = within(optionsList).getAllByRole('option')
const selectAllOption =
options.find(
(option) =>
option.textContent?.includes('Select all') ||
option.getAttribute('data-testid') === 'select-all',
) || options[0]
fireEvent.click(selectAllOption)
await waitFor(() => {
expect(onChange).toHaveBeenCalledWith({ selectedItems: items })
})
fireEvent.click(selectAllOption)
await waitFor(() => {
expect(onChange).toHaveBeenCalledWith({ selectedItems: [] })
})
})
it('Can deselect complex options', async () => {
const onChange = jest.fn()
const opts = [
{ label: 'Its', value: 'relationship' },
{ label: 'Complicated', value: 'status' },
]
render(
<Autocomplete
optionLabel={(o) => o.label}
itemToKey={(item) => item?.value}
label={labelText}
options={opts}
data-testid="styled-autocomplete"
multiple={true}
onOptionsChange={onChange}
selectedOptions={[
{
label: 'Its',
value: 'relationship',
},
]}
/>,
)
const labeledNodes = await screen.findAllByLabelText(labelText)
const optionsList = labeledNodes[1]
const buttonNode = await screen.findByLabelText('toggle options', {
selector: 'button',
})
fireEvent.click(buttonNode)
await waitFor(() => {
const options = within(optionsList).queryAllByRole('option')
expect(options.length).toBeGreaterThanOrEqual(2)
})
const options = within(optionsList).getAllByRole('option')
const firstValidOption = options.find((option) => {
const text = option.textContent?.trim()
return text && text.length > 0 && text !== ''
})
if (firstValidOption) {
fireEvent.click(firstValidOption)
}
await waitFor(() => {
expect(onChange).toHaveBeenCalledWith({ selectedItems: [] })
})
})
it('Can open the options on button click', async () => {
render(<Autocomplete options={items} label={labelText} />)
const labeledNodes = await screen.findAllByLabelText(labelText)
const optionsList = labeledNodes[1]
const buttonNode = await screen.findByLabelText('toggle options', {
selector: 'button',
})
expect(optionsList.childNodes).toHaveLength(0)
fireEvent.click(buttonNode)
await waitForVirtualizedOptions(optionsList, 3)
})
type ControlledProps = {
onOptionsChange: () => void
}
const ControlledAutoComplete = ({ onOptionsChange }: ControlledProps) => {
const [selected, setSelected] = useState<string[]>([])
return (
<Autocomplete
multiple
options={items}
label={labelText}
selectedOptions={selected}
onOptionsChange={(changes) => {
setSelected(changes.selectedItems)
onOptionsChange()
}}
/>
)
}
it('Can be a controlled component', async () => {
const handleChange = jest.fn()
render(<ControlledAutoComplete onOptionsChange={handleChange} />)
const labeledNodes = await screen.findAllByLabelText(labelText)
const optionsList = labeledNodes[1]
const buttonNode = await screen.findByLabelText('toggle options', {
selector: 'button',
})
await waitFor(() => {
expect(handleChange).toHaveBeenCalledTimes(0)
})
fireEvent.click(buttonNode)
const options = await waitForVirtualizedOptions(optionsList, 3)
fireEvent.click(options[2])
await waitFor(() => {
expect(handleChange).toHaveBeenCalledTimes(1)
})
})
it('Can filter results by input value', async () => {
render(<Autocomplete options={items} label={labelText} />)
const labeledNodes = await screen.findAllByLabelText(labelText)
const input = labeledNodes[0]
const optionsList = labeledNodes[1]
const buttonNode = await screen.findByLabelText('toggle options', {
selector: 'button',
})
expect(optionsList.childNodes).toHaveLength(0)
fireEvent.click(buttonNode)
await waitForVirtualizedOptions(optionsList, 3)
fireEvent.change(input, {
target: { value: 'ree' },
})
await waitFor(() => {
const options = within(optionsList).queryAllByRole('option')
const validOptions = options.filter((option) => {
const text = option.textContent?.trim()
return text && text.includes('Three')
})
expect(validOptions.length).toBeGreaterThanOrEqual(1)
})
const allOptions = within(optionsList).getAllByRole('option')
const filteredOptions = allOptions.filter((option) => {
const text = option.textContent?.trim()
return text && text.includes('Three')
})
expect(filteredOptions.length).toBeGreaterThanOrEqual(1)
expect(filteredOptions[0]).toHaveTextContent('Three')
})
it('Second option is first when first option is disabled', async () => {
render(
<Autocomplete
options={items}
label={labelText}
optionDisabled={(item) => item === items[0]}
/>,
)
const labeledNodes = await screen.findAllByLabelText(labelText)
const input = labeledNodes[0]
const optionsList = labeledNodes[1]
fireEvent.keyDown(input, { key: 'ArrowDown' })
await waitFor(() => {
const options = within(optionsList).queryAllByRole('option')
expect(options.length).toBeGreaterThan(0)
})
const options = within(optionsList).getAllByRole('option')
expect(options).toHaveLength(2) // since one option is disabled
expect(await within(options[0]).findByText(items[1])).toBeDefined()
const withDisabledOptions = await within(optionsList).findAllByRole(
'option',
{
hidden: true,
},
)
expect(withDisabledOptions[0]).toHaveAttribute('aria-hidden')
expect(
await within(withDisabledOptions[0]).findByText(items[0]),
).toBeDefined()
})
it('Clears the input text on blur when no option is selected', async () => {
render(<Autocomplete options={items} label={labelText} />)
const labeledNodes = await screen.findAllByLabelText(labelText)
const input = labeledNodes[0]
fireEvent.change(input, {
target: { value: 'ree' },
})
fireEvent.blur(input)
expect(input).toHaveValue('')
})
it('Correctly handles keypresses up/down when all options are disabled', async () => {
render(
<Autocomplete
options={items}
label={labelText}
// Somewhat contrived condition to emulate a scenario where an undefined item would return true for the 'option' being disabled
optionDisabled={(item) => item !== items[0]}
/>,
)
const labeledNodes = await screen.findAllByLabelText(labelText)
const input = labeledNodes[0]
const optionsList = labeledNodes[1]
fireEvent.keyDown(input, { key: 'ArrowDown' })
await waitFor(() => {
const options = within(optionsList).queryAllByRole('option')
expect(options.length).toBeGreaterThan(0)
})
const options = within(optionsList).getAllByRole('option')
expect(options).toHaveLength(1) // since all but one options are disabled
fireEvent.change(input, {
target: { value: 'asfsggsdhfj' },
})
await waitFor(() => {
const optionsAfterSearch = within(optionsList).queryAllByRole('option')
expect(optionsAfterSearch).toHaveLength(0) // since all are filtered out
})
// Prevent regression: key up/down when options are disabled causes infinite loop
fireEvent.keyDown(input, { key: 'ArrowDown' })
fireEvent.blur(input)
expect(input).toHaveValue('')
})
it('Can extend the css for the component & props are passed correctly to input', async () => {
const { container } = render(
<StyledAutocomplete
optionLabel={(option: unknown) => option as string}
label="test"
options={items}
data-testid="styled-autocomplete"
style={{ margin: '3px' }}
/>,
)
const autocomplete = await screen.findByTestId('styled-autocomplete')
// CSS testing requires access to container - this is a legitimate testing pattern
// eslint-disable-next-line testing-library/no-node-access
expect(container.firstChild).toHaveStyle('margin: 3px')
expect(autocomplete.nodeName).toBe('INPUT')
})
})
describe('Autocomplete: Add new options feature', () => {
it('Can add new options', async () => {
const onChange = jest.fn()
const onAddNewOption = jest.fn()
render(
<StyledAutocomplete
label={labelText}
options={items}
data-testid="styled-autocomplete"
onOptionsChange={onChange}
onAddNewOption={onAddNewOption}
/>,
)
const labeledNodes = await screen.findAllByLabelText(labelText)
const input = labeledNodes[0]
const optionsList = labeledNodes[1]
const buttonNode = await screen.findByLabelText('toggle options', {
selector: 'button',
})
fireEvent.click(buttonNode)
fireEvent.change(input, {
target: { value: 'New option' },
})
const options = await within(optionsList).findAllByRole('option')
fireEvent.click(options[0])
await waitFor(() => {
expect(onAddNewOption).toHaveBeenNthCalledWith(1, 'New option')
})
})
it('Can add new option using arrow down and Enter key', async () => {
const onAddNewOption = jest.fn()
render(
<StyledAutocomplete
label={labelText}
options={items}
data-testid="styled-autocomplete"
onAddNewOption={onAddNewOption}
/>,
)
const labeledNodes = await screen.findAllByLabelText(labelText)
const input = labeledNodes[0]
const optionsList = labeledNodes[1]
const buttonNode = await screen.findByLabelText('toggle options', {
selector: 'button',
})
fireEvent.click(buttonNode)
fireEvent.change(input, {
target: { value: 'New option via arrow+enter' },
})
const addOption = await within(optionsList).findByTestId('add-item')
expect(addOption).toBeInTheDocument()
// Use arrow down to highlight the add option, then Enter
fireEvent.keyDown(input, { key: 'ArrowDown', code: 'ArrowDown' })
fireEvent.keyDown(input, { key: 'Enter', code: 'Enter' })
await waitFor(() => {
expect(onAddNewOption).toHaveBeenCalledWith('New option via arrow+enter')
})
})
it('Does not call onAddNewOption with empty string', async () => {
const onAddNewOption = jest.fn()
render(
<StyledAutocomplete
label={labelText}
options={items}
data-testid="styled-autocomplete"
onAddNewOption={onAddNewOption}
/>,
)
const labeledNodes = await screen.findAllByLabelText(labelText)
const input = labeledNodes[0]
fireEvent.focus(input)
fireEvent.change(input, {
target: { value: ' ' },
})
fireEvent.keyDown(input, { key: 'Enter', code: 'Enter' })
expect(onAddNewOption).not.toHaveBeenCalled()
})
it('Clears input after adding new option', async () => {
const onAddNewOption = jest.fn()
render(
<StyledAutocomplete
label={labelText}
options={items}
data-testid="styled-autocomplete"
onAddNewOption={onAddNewOption}
/>,
)
const labeledNodes = await screen.findAllByLabelText(labelText)
const input = labeledNodes[0] as HTMLInputElement
const optionsList = labeledNodes[1]
const buttonNode = await screen.findByLabelText('toggle options', {
selector: 'button',
})
fireEvent.click(buttonNode)
fireEvent.change(input, {
target: { value: 'New option to clear' },
})
const options = await within(optionsList).findAllByRole('option')
fireEvent.click(options[0])
await waitFor(() => {
expect(onAddNewOption).toHaveBeenCalledWith('New option to clear')
})
expect(input.value).toBe('')
})
it('Displays correct aria-label for add option', async () => {
const onAddNewOption = jest.fn()
render(
<StyledAutocomplete
label={labelText}
options={items}
data-testid="styled-autocomplete"
onAddNewOption={onAddNewOption}
/>,
)
const labeledNodes = await screen.findAllByLabelText(labelText)
const input = labeledNodes[0]
const buttonNode = await screen.findByLabelText('toggle options', {
selector: 'button',
})
fireEvent.click(buttonNode)
fireEvent.change(input, {
target: { value: 'Test option' },
})
const addOption = await screen.findByTestId('add-item')
expect(addOption).toHaveAttribute(
'aria-label',
'Add new option: Test option',
)
})
it('Does not show add option when onAddNewOption is not provided', async () => {
render(
<StyledAutocomplete
label={labelText}
options={items}
data-testid="styled-autocomplete"
// no onAddNewOption prop
/>,
)
const labeledNodes = await screen.findAllByLabelText(labelText)
const input = labeledNodes[0]
const buttonNode = await screen.findByLabelText('toggle options', {
selector: 'button',
})
fireEvent.click(buttonNode)
fireEvent.change(input, {
target: { value: 'Should not show add option' },
})
const addOption = screen.queryByTestId('add-item')
expect(addOption).not.toBeInTheDocument()
})
})
describe('Autocomplete: Scroll position and navigation memory', () => {
const longItemsList = Array.from({ length: 20 }, (_, i) => `Option ${i + 1}`)
const uniqueLabelText = 'Scroll test autocomplete'
it('Maintains selected option when reopening single-select', async () => {
const AutocompleteWithState = () => {
const [selectedItem, setSelectedItem] = useState<string | null>(null)
return (
<Autocomplete
label={uniqueLabelText}
options={longItemsList}
multiple={false}
selectedOptions={selectedItem ? [selectedItem] : []}
onOptionsChange={(changes) => {
if (changes.selectedItems.length > 0) {
setSelectedItem(changes.selectedItems[0])
}
}}
/>
)
}
render(<AutocompleteWithState />)
const input = screen.getByRole('combobox')
// Open autocomplete and select option 5
fireEvent.click(input)
await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(20))
for (let i = 0; i < 4; i++) {
fireEvent.keyDown(input, { key: 'ArrowDown' })
}
fireEvent.keyDown(input, { key: 'Enter' })
await waitFor(() =>
expect(screen.queryByRole('option')).not.toBeInTheDocument(),
)
expect(input).toHaveValue('Option 5')
// Reopen - should maintain selection
fireEvent.click(input)
await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(20))
expect(input).toHaveValue('Option 5')
})
it('Keyboard navigation works correctly with preselected option', async () => {
render(
<Autocomplete
label={uniqueLabelText}
options={longItemsList}
multiple={false}
selectedOptions={['Option 5']}
/>,
)
const input = screen.getByRole('combobox')
expect(input).toHaveValue('Option 5')
fireEvent.click(input)
await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(20))
// Wait for scroll restoration (component uses 10ms setTimeout for scroll positioning)
await new Promise((resolve) => setTimeout(resolve, 50))
// Get current highlighted option ID
const currentHighlightedId = input.getAttribute('aria-activedescendant')
expect(currentHighlightedId).toBeTruthy()
// Verify the selected option (Option 5) is visible in the dropdown
expect(screen.getByRole('option', { name: 'Option 5' })).toBeDefined()
// Test arrow down navigation from current position
fireEvent.keyDown(input, { key: 'ArrowDown' })
await waitFor(() => {
const newHighlightedId = input.getAttribute('aria-activedescendant')
expect(newHighlightedId).not.toBe(currentHighlightedId)
})
// Test arrow up navigation goes back
fireEvent.keyDown(input, { key: 'ArrowUp' })
await waitFor(() => {
expect(input.getAttribute('aria-activedescendant')).toBe(
currentHighlightedId,
)
})
})
it('Handles empty selection correctly', async () => {
render(
<Autocomplete
label={uniqueLabelText}
options={longItemsList}
multiple={false}
/>,
)
const input = screen.getByRole('combobox')
fireEvent.click(input)
await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(20))
expect(input).toHaveAttribute('aria-activedescendant')
fireEvent.keyDown(input, { key: 'Escape' })
await waitFor(() =>
expect(screen.queryByRole('option')).not.toBeInTheDocument(),
)
fireEvent.click(input)
await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(20))
expect(input).toHaveAttribute('aria-activedescendant')
})
it('Multiselect behavior remains unchanged', async () => {
render(
<Autocomplete
label={uniqueLabelText}
options={longItemsList}
multiple={true}
/>,
)
const input = screen.getByRole('combobox')
fireEvent.click(input)
await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(20))
fireEvent.keyDown(input, { key: 'ArrowDown' })
fireEvent.keyDown(input, { key: 'Enter' })
fireEvent.keyDown(input, { key: 'ArrowDown' })
fireEvent.keyDown(input, { key: 'Enter' })
expect(screen.getAllByRole('option')).toHaveLength(20)
expect(input).toHaveAttribute('placeholder', '2/20 selected')
})
it('Preserves behavior across open/close cycles', async () => {
const AutocompleteWithState = () => {
const [selectedItem, setSelectedItem] = useState<string>('Option 8')
return (
<Autocomplete
label={uniqueLabelText}
options={longItemsList}
multiple={false}
selectedOptions={[selectedItem]}
onOptionsChange={(changes) => {
if (changes.selectedItems.length > 0) {
setSelectedItem(changes.selectedItems[0])
}
}}
/>
)
}
render(<AutocompleteWithState />)
const input = screen.getByRole('combobox')
expect(input).toHaveValue('Option 8')
fireEvent.click(input)
await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(20))
fireEvent.keyDown(input, { key: 'Escape' })
await waitFor(() =>
expect(screen.queryByRole('option')).not.toBeInTheDocument(),
)
fireEvent.click(input)
await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(20))
expect(input).toHaveValue('Option 8')
})
it('Shows chips when selectionDisplay is set to chips', async () => {
render(
<Autocomplete
label={labelText}
options={items}
multiple
selectionDisplay="chips"
initialSelectedOptions={['One', 'Two']}
/>,
)
const chip1 = await screen.findByText('One')
const chip2 = await screen.findByText('Two')
expect(chip1).toBeInTheDocument()
expect(chip2).toBeInTheDocument()
})
it('Removes chip when clicking the chip remove button', async () => {
const handleChange = jest.fn()
render(
<Autocomplete
label={labelText}
options={items}
multiple
selectionDisplay="chips"
initialSelectedOptions={['One', 'Two']}
onOptionsChange={handleChange}
/>,
)
const chip1 = await screen.findByText('One')
expect(chip1).toBeInTheDocument()
const closeIcons = screen.getAllByTitle('close')
fireEvent.click(closeIcons[0])
await waitFor(() => {
expect(handleChange).toHaveBeenCalledWith({ selectedItems: ['Two'] })
})
})
it('Moves focus to next chip when removing a chip with Enter key', async () => {
render(
<Autocomplete
label={labelText}
options={items}
multiple
selectionDisplay="chips"
initialSelectedOptions={['One', 'Two', 'Three']}
/>,
)
const chip1 = await screen.findByText('One')
const chip2 = await screen.findByText('Two')
expect(chip1).toBeInTheDocument()
expect(chip2).toBeInTheDocument()
const chip1Button = screen.getByRole('button', { name: /One/i })
chip1Button?.focus()
fireEvent.keyDown(chip1Button, { key: 'Enter' })
await waitFor(() => {
expect(screen.queryByText('One')).not.toBeInTheDocument()
})
const chip2Button = screen.getByRole('button', { name: /Two/i })
expect(chip2Button).toHaveFocus()
})
})