forked from mui/base-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCheckboxGroup.test.tsx
More file actions
1965 lines (1643 loc) · 68.4 KB
/
Copy pathCheckboxGroup.test.tsx
File metadata and controls
1965 lines (1643 loc) · 68.4 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
import { expect, vi } from 'vitest';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { useIsoLayoutEffect } from '@base-ui/utils/useIsoLayoutEffect';
import { createRenderer, screen, fireEvent } from '@mui/internal-test-utils';
import { CheckboxGroup } from '@base-ui/react/checkbox-group';
import { Checkbox } from '@base-ui/react/checkbox';
import { Field } from '@base-ui/react/field';
import { Form } from '@base-ui/react/form';
import { describeConformance, isJSDOM } from '#test-utils';
describe('<CheckboxGroup />', () => {
const { render } = createRenderer();
describeConformance(<CheckboxGroup />, () => ({
inheritComponent: 'div',
refInstanceof: window.HTMLDivElement,
render,
}));
describe('prop: id', () => {
it('is forwarded to the root element', () => {
render(<CheckboxGroup id="group-id" />);
expect(screen.getByRole('group')).toHaveAttribute('id', 'group-id');
});
});
describe('prop: value', () => {
it('should control the value', () => {
function App() {
const [value, setValue] = React.useState(['red']);
return (
<CheckboxGroup value={value} onValueChange={setValue}>
<Checkbox.Root name="red" data-testid="red" />
<Checkbox.Root name="green" data-testid="green" />
<Checkbox.Root name="blue" data-testid="blue" />
</CheckboxGroup>
);
}
render(<App />);
const red = screen.getByTestId('red');
const green = screen.getByTestId('green');
const blue = screen.getByTestId('blue');
expect(red).toHaveAttribute('aria-checked', 'true');
expect(green).toHaveAttribute('aria-checked', 'false');
expect(blue).toHaveAttribute('aria-checked', 'false');
fireEvent.click(green);
expect(red).toHaveAttribute('aria-checked', 'true');
expect(green).toHaveAttribute('aria-checked', 'true');
expect(blue).toHaveAttribute('aria-checked', 'false');
fireEvent.click(blue);
expect(red).toHaveAttribute('aria-checked', 'true');
expect(green).toHaveAttribute('aria-checked', 'true');
expect(blue).toHaveAttribute('aria-checked', 'true');
fireEvent.click(green);
expect(red).toHaveAttribute('aria-checked', 'true');
expect(green).toHaveAttribute('aria-checked', 'false');
expect(blue).toHaveAttribute('aria-checked', 'true');
});
it('supports an empty string item value', () => {
function App() {
const [value, setValue] = React.useState(['']);
return (
<CheckboxGroup value={value} onValueChange={setValue}>
<Checkbox.Root value="" data-testid="empty" />
<Checkbox.Root value="other" data-testid="other" />
</CheckboxGroup>
);
}
render(<App />);
const empty = screen.getByTestId('empty');
const other = screen.getByTestId('other');
expect(empty).toHaveAttribute('aria-checked', 'true');
expect(other).toHaveAttribute('aria-checked', 'false');
fireEvent.click(empty);
expect(empty).toHaveAttribute('aria-checked', 'false');
});
it('treats a controlled value that becomes undefined as an empty array', () => {
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
function App() {
const [value, setValue] = React.useState<string[] | undefined>(['red']);
return (
<React.Fragment>
<CheckboxGroup value={value}>
<Checkbox.Root value="red" data-testid="red" />
</CheckboxGroup>
<button type="button" onClick={() => setValue(undefined)}>
Clear
</button>
</React.Fragment>
);
}
try {
render(<App />);
expect(screen.getByTestId('red')).toHaveAttribute('aria-checked', 'true');
fireEvent.click(screen.getByText('Clear'));
expect(screen.getByTestId('red')).toHaveAttribute('aria-checked', 'false');
} finally {
consoleError.mockRestore();
}
});
});
describe('prop: onValueChange', () => {
it('should be called when the value changes', () => {
const handleValueChange = vi.fn();
function App() {
const [value, setValue] = React.useState<string[]>([]);
return (
<CheckboxGroup
value={value}
onValueChange={(nextValue) => {
setValue(nextValue);
handleValueChange(nextValue);
}}
>
<Checkbox.Root name="red" data-testid="red" />
<Checkbox.Root name="green" data-testid="green" />
<Checkbox.Root name="blue" data-testid="blue" />
</CheckboxGroup>
);
}
render(<App />);
const red = screen.getByTestId('red');
const green = screen.getByTestId('green');
const blue = screen.getByTestId('blue');
fireEvent.click(red);
expect(handleValueChange.mock.calls.length).toBe(1);
expect(handleValueChange.mock.calls[0][0]).toEqual(['red']);
fireEvent.click(green);
expect(handleValueChange.mock.calls.length).toBe(2);
expect(handleValueChange.mock.calls[1][0]).toEqual(['red', 'green']);
fireEvent.click(blue);
expect(handleValueChange.mock.calls.length).toBe(3);
expect(handleValueChange.mock.calls[2][0]).toEqual(['red', 'green', 'blue']);
});
it('should treat an omitted defaultValue as an empty array', () => {
const handleValueChange = vi.fn();
render(
<CheckboxGroup onValueChange={handleValueChange}>
<Checkbox.Root name="red" data-testid="red" />
<Checkbox.Root name="green" data-testid="green" />
<Checkbox.Root name="blue" data-testid="blue" />
</CheckboxGroup>,
);
const red = screen.getByTestId('red');
const green = screen.getByTestId('green');
fireEvent.click(red);
expect(handleValueChange.mock.calls[0][0]).toEqual(['red']);
fireEvent.click(green);
expect(handleValueChange.mock.calls[1][0]).toEqual(['red', 'green']);
fireEvent.click(red);
expect(handleValueChange.mock.calls[2][0]).toEqual(['green']);
});
it('does not update the group when onValueChange cancels the event', () => {
const handleValueChange = vi.fn((_, eventDetails: CheckboxGroup.ChangeEventDetails) => {
eventDetails.cancel();
});
render(
<CheckboxGroup onValueChange={handleValueChange}>
<Checkbox.Root value="red" data-testid="red" />
<Checkbox.Root value="green" data-testid="green" />
</CheckboxGroup>,
);
const red = screen.getByTestId('red');
const green = screen.getByTestId('green');
fireEvent.click(red);
expect(handleValueChange.mock.calls.length).toBe(1);
expect(handleValueChange.mock.calls[0][0]).toEqual(['red']);
expect(red).toHaveAttribute('aria-checked', 'false');
expect(green).toHaveAttribute('aria-checked', 'false');
});
});
describe('prop: defaultValue', () => {
it('should set the initial value', () => {
function App() {
return (
<CheckboxGroup defaultValue={['red']}>
<Checkbox.Root name="red" data-testid="red" />
<Checkbox.Root name="green" data-testid="green" />
<Checkbox.Root name="blue" data-testid="blue" />
</CheckboxGroup>
);
}
render(<App />);
const red = screen.getByTestId('red');
const green = screen.getByTestId('green');
const blue = screen.getByTestId('blue');
expect(red).toHaveAttribute('aria-checked', 'true');
expect(green).toHaveAttribute('aria-checked', 'false');
expect(blue).toHaveAttribute('aria-checked', 'false');
fireEvent.click(green);
expect(red).toHaveAttribute('aria-checked', 'true');
expect(green).toHaveAttribute('aria-checked', 'true');
expect(blue).toHaveAttribute('aria-checked', 'false');
});
it('keeps omitted defaults isolated between groups in Strict Mode', async () => {
const { user } = render(
<React.StrictMode>
<CheckboxGroup allValues={['a-1', 'a-2']}>
<Checkbox.Root parent data-testid="a-parent" />
<Checkbox.Root value="a-1" data-testid="a-1" />
<Checkbox.Root value="a-2" data-testid="a-2" />
</CheckboxGroup>
<CheckboxGroup allValues={['b-1', 'b-2']}>
<Checkbox.Root parent data-testid="b-parent" />
<Checkbox.Root value="b-1" data-testid="b-1" />
<Checkbox.Root value="b-2" data-testid="b-2" />
</CheckboxGroup>
</React.StrictMode>,
);
const aParent = screen.getByTestId('a-parent');
const a1 = screen.getByTestId('a-1');
const a2 = screen.getByTestId('a-2');
const bParent = screen.getByTestId('b-parent');
const b1 = screen.getByTestId('b-1');
const b2 = screen.getByTestId('b-2');
await user.click(a1);
expect(aParent).toHaveAttribute('aria-checked', 'mixed');
expect(bParent).toHaveAttribute('aria-checked', 'false');
expect(b1).toHaveAttribute('aria-checked', 'false');
expect(b2).toHaveAttribute('aria-checked', 'false');
await user.click(bParent);
expect(b1).toHaveAttribute('aria-checked', 'true');
expect(b2).toHaveAttribute('aria-checked', 'true');
expect(a1).toHaveAttribute('aria-checked', 'true');
expect(a2).toHaveAttribute('aria-checked', 'false');
await user.click(aParent);
expect(a1).toHaveAttribute('aria-checked', 'true');
expect(a2).toHaveAttribute('aria-checked', 'true');
expect(bParent).toHaveAttribute('aria-checked', 'true');
await user.click(b1);
expect(bParent).toHaveAttribute('aria-checked', 'mixed');
expect(aParent).toHaveAttribute('aria-checked', 'true');
});
});
describe('prop: disabled', () => {
it('disables all checkboxes when `true`', () => {
function App() {
return (
<CheckboxGroup disabled>
<Checkbox.Root name="red" data-testid="red" />
<Checkbox.Root name="green" data-testid="green" />
<Checkbox.Root name="blue" data-testid="blue" />
</CheckboxGroup>
);
}
render(<App />);
const red = screen.getByTestId('red');
const green = screen.getByTestId('green');
const blue = screen.getByTestId('blue');
expect(red).toHaveAttribute('aria-disabled', 'true');
expect(green).toHaveAttribute('aria-disabled', 'true');
expect(blue).toHaveAttribute('aria-disabled', 'true');
});
it('does not disable all checkboxes when `false`', () => {
function App() {
return (
<CheckboxGroup disabled={false}>
<Checkbox.Root name="red" data-testid="red" />
<Checkbox.Root name="green" data-testid="green" />
<Checkbox.Root name="blue" data-testid="blue" />
</CheckboxGroup>
);
}
render(<App />);
const red = screen.getByTestId('red');
const green = screen.getByTestId('green');
const blue = screen.getByTestId('blue');
expect(red).not.toHaveAttribute('aria-disabled', 'true');
expect(green).not.toHaveAttribute('aria-disabled', 'true');
expect(blue).not.toHaveAttribute('aria-disabled', 'true');
});
it('takes precedence over individual checkboxes', () => {
function App() {
return (
<CheckboxGroup disabled>
<Checkbox.Root name="red" data-testid="red" disabled={false} />
<Checkbox.Root name="green" data-testid="green" />
<Checkbox.Root name="blue" data-testid="blue" />
</CheckboxGroup>
);
}
render(<App />);
const red = screen.getByTestId('red');
const green = screen.getByTestId('green');
const blue = screen.getByTestId('blue');
expect(red).toHaveAttribute('aria-disabled', 'true');
expect(green).toHaveAttribute('aria-disabled', 'true');
expect(blue).toHaveAttribute('aria-disabled', 'true');
});
});
describe('Field', () => {
it('keeps a required error while another required checkbox in the group is unchecked', async () => {
const { user } = render(
<Form onSubmit={(event) => event.preventDefault()}>
<Field.Root name="protocols">
<CheckboxGroup defaultValue={[]}>
<Field.Item>
<Checkbox.Root value="http" data-testid="checkbox" required />
</Field.Item>
<Field.Item>
<Checkbox.Root value="https" data-testid="checkbox" required />
</Field.Item>
</CheckboxGroup>
<Field.Error match="valueMissing" data-testid="error">
required
</Field.Error>
</Field.Root>
<button type="submit">submit</button>
</Form>,
);
const checkboxes = screen.getAllByTestId('checkbox');
await user.click(screen.getByText('submit'));
expect(screen.getByTestId('error')).toHaveTextContent('required');
// Checking only one of the two required checkboxes must not clear the error.
await user.click(checkboxes[1]);
await user.click(screen.getByText('submit'));
expect(screen.getByTestId('error')).toHaveTextContent('required');
await user.click(checkboxes[0]);
await user.click(screen.getByText('submit'));
expect(screen.queryByTestId('error')).toBe(null);
});
it('ignores a disabled required checkbox when validating the group', async () => {
const { user } = render(
<Form onSubmit={(event) => event.preventDefault()}>
<Field.Root name="protocols">
<CheckboxGroup defaultValue={[]}>
<Field.Item>
<Checkbox.Root value="https" data-testid="cb-enabled" required />
</Field.Item>
{/* Mounted last so it would otherwise win the shared input ref. */}
<Field.Item>
<Checkbox.Root value="http" data-testid="cb-disabled" required disabled />
</Field.Item>
</CheckboxGroup>
<Field.Error match="valueMissing" data-testid="error">
required
</Field.Error>
</Field.Root>
<button type="submit">submit</button>
</Form>,
);
await user.click(screen.getByText('submit'));
expect(screen.getByTestId('error')).toHaveTextContent('required');
// A disabled checkbox is exempt from constraint validation, so checking the only
// enabled required checkbox is enough to satisfy the field.
await user.click(screen.getByTestId('cb-enabled'));
await user.click(screen.getByText('submit'));
expect(screen.queryByTestId('error')).toBe(null);
});
it('keeps validating the remaining required checkbox after a checked sibling unmounts', async () => {
function App() {
const [showHttps, setShowHttps] = React.useState(true);
return (
<Form onSubmit={(event) => event.preventDefault()}>
<Field.Root name="protocols">
<CheckboxGroup defaultValue={[]}>
<Field.Item>
<Checkbox.Root value="http" data-testid="checkbox-http" required />
</Field.Item>
{showHttps && (
<Field.Item>
<Checkbox.Root value="https" data-testid="checkbox-https" required />
</Field.Item>
)}
</CheckboxGroup>
<Field.Error match="valueMissing" data-testid="error">
required
</Field.Error>
</Field.Root>
<button type="button" onClick={() => setShowHttps(false)}>
remove
</button>
<button type="submit">submit</button>
</Form>
);
}
const { user } = render(<App />);
await user.click(screen.getByText('submit'));
expect(screen.getByTestId('error')).toHaveTextContent('required');
// Check `https` (the last-mounted input that wins the shared ref), then unmount it. The shared
// ref is now nulled, so only the registry can keep validating the still-unchecked `http`.
await user.click(screen.getByTestId('checkbox-https'));
await user.click(screen.getByText('remove'));
await user.click(screen.getByText('submit'));
expect(screen.getByTestId('error')).toHaveTextContent('required');
// Checking the remaining required checkbox satisfies the field.
await user.click(screen.getByTestId('checkbox-http'));
await user.click(screen.getByText('submit'));
expect(screen.queryByTestId('error')).toBe(null);
});
it('validationMode=onChange keeps the error until every required checkbox is ticked', async () => {
const { user } = render(
<Field.Root name="protocols" validationMode="onChange">
<CheckboxGroup defaultValue={[]}>
<Field.Item>
<Checkbox.Root value="http" data-testid="cb-http" required />
</Field.Item>
<Field.Item>
<Checkbox.Root value="https" data-testid="cb-https" required />
</Field.Item>
</CheckboxGroup>
<Field.Error match="valueMissing" data-testid="error">
required
</Field.Error>
</Field.Root>,
);
expect(screen.queryByTestId('error')).toBe(null);
// Ticking the second (last-mounted) checkbox must not clear the requirement on the first.
await user.click(screen.getByTestId('cb-https'));
expect(screen.getByTestId('error')).toHaveTextContent('required');
await user.click(screen.getByTestId('cb-http'));
expect(screen.queryByTestId('error')).toBe(null);
});
it('validationMode=onBlur keeps the error until every required checkbox is ticked', async () => {
const { user } = render(
<Field.Root name="protocols" validationMode="onBlur">
<CheckboxGroup defaultValue={[]}>
<Field.Item>
<Checkbox.Root value="http" data-testid="cb-http" required />
</Field.Item>
<Field.Item>
<Checkbox.Root value="https" data-testid="cb-https" required />
</Field.Item>
</CheckboxGroup>
<Field.Error match="valueMissing" data-testid="error">
required
</Field.Error>
</Field.Root>,
);
await user.click(screen.getByTestId('cb-https'));
expect(screen.queryByTestId('error')).toBe(null);
fireEvent.blur(screen.getByTestId('cb-https'));
expect(screen.getByTestId('error')).toHaveTextContent('required');
await user.click(screen.getByTestId('cb-http'));
expect(screen.queryByTestId('error')).toBe(null);
});
it('does not leave a stale custom error when toggling checkboxes in a group', async () => {
const validateSpy = vi.fn((value) => ((value as string[]).length < 2 ? 'pick two' : null));
render(
<Field.Root name="protocols" validationMode="onChange" validate={validateSpy}>
<CheckboxGroup defaultValue={[]}>
<Field.Item>
<Checkbox.Root value="http" data-testid="cb-http" />
</Field.Item>
<Field.Item>
<Checkbox.Root value="https" data-testid="cb-https" />
</Field.Item>
</CheckboxGroup>
</Field.Root>,
);
const http = screen.getByTestId('cb-http');
const https = screen.getByTestId('cb-https');
fireEvent.click(http);
expect(http).toHaveAttribute('aria-invalid', 'true');
// Selecting both clears the field-level error; no stale custom validation result should keep
// the group invalid.
fireEvent.click(https);
expect(http).not.toHaveAttribute('aria-invalid');
expect(https).not.toHaveAttribute('aria-invalid');
// Unticking one brings the real error back (not a phantom from a prior commit).
fireEvent.click(http);
expect(https).toHaveAttribute('aria-invalid', 'true');
});
it('clears custom validity from disabled registered inputs when the group becomes valid', async () => {
function App() {
const [disabled, setDisabled] = React.useState(false);
const [value, setValue] = React.useState<string[]>([]);
const validate = (nextValue: unknown) =>
(nextValue as string[]).length < 2 ? 'pick two' : null;
return (
<Field.Root name="protocols" validationMode="onChange" validate={validate}>
<CheckboxGroup value={value} onValueChange={setValue}>
<Field.Item>
<Checkbox.Root value="http" data-testid="cb-http" disabled={disabled} />
</Field.Item>
<Field.Item>
<Checkbox.Root value="https" data-testid="cb-https" />
</Field.Item>
</CheckboxGroup>
<button type="button" onClick={() => setDisabled(true)}>
disable
</button>
</Field.Root>
);
}
const { user } = render(<App />);
await user.click(screen.getByTestId('cb-http'));
const httpInput = document.querySelector<HTMLInputElement>(
'input[type="checkbox"][value="http"]',
);
expect(httpInput?.validity.customError).toBe(true);
await user.click(screen.getByText('disable'));
await user.click(screen.getByTestId('cb-https'));
expect(httpInput?.validity.customError).toBe(false);
});
it('keeps a custom validity message set outside the field on a registered input when submitting', async () => {
const onFormSubmit = vi.fn();
const { user } = render(
<Form onFormSubmit={onFormSubmit}>
<Field.Root name="protocols">
<CheckboxGroup defaultValue={[]}>
<Field.Item>
<Checkbox.Root value="http" data-testid="cb-http" />
</Field.Item>
<Field.Item>
<Checkbox.Root value="https" data-testid="cb-https" />
</Field.Item>
</CheckboxGroup>
<Field.Error data-testid="error" />
</Field.Root>
<button type="submit">submit</button>
</Form>,
);
// The hidden inputs only carry their `value` attribute while checked, so select by position.
const httpInput = document.querySelectorAll<HTMLInputElement>('input[type="checkbox"]')[0];
httpInput.setCustomValidity('external error');
await user.click(screen.getByText('submit'));
expect(onFormSubmit).not.toHaveBeenCalled();
expect(httpInput.validationMessage).toBe('external error');
expect(screen.getByTestId('error')).toHaveTextContent('external error');
});
it('prop: validationMode=onSubmit', async () => {
const validateSpy = vi.fn((value) => {
const v = value as string[];
if (v.length === 0) {
return 'custom error 1';
}
if (v.length < 2) {
return 'custom error 2';
}
if (v.includes('two')) {
return 'custom error 3';
}
return null;
});
const { user } = render(
<Form>
<Field.Root validate={validateSpy} name="test">
<CheckboxGroup defaultValue={[]}>
<Field.Item>
<Checkbox.Root value="one" data-testid="checkbox" />
</Field.Item>
<Field.Item>
<Checkbox.Root value="two" data-testid="checkbox" />
</Field.Item>
<Field.Item>
<Checkbox.Root value="three" data-testid="checkbox" />
</Field.Item>
</CheckboxGroup>
</Field.Root>
<button type="submit">submit</button>
</Form>,
);
const checkboxes = screen.getAllByTestId('checkbox');
const [checkbox1, checkbox2, checkbox3] = checkboxes;
checkboxes.forEach((checkbox) => expect(checkbox).not.toHaveAttribute('aria-invalid'));
await user.click(checkbox2);
checkboxes.forEach((checkbox) => expect(checkbox).not.toHaveAttribute('aria-invalid'));
await user.click(screen.getByText('submit'));
checkboxes.forEach((checkbox) => expect(checkbox).toHaveAttribute('aria-invalid'));
await user.click(checkbox1);
expect(validateSpy.mock.lastCall?.[0]).toEqual(['two', 'one']);
checkboxes.forEach((checkbox) => expect(checkbox).toHaveAttribute('aria-invalid'));
await user.click(checkbox2);
await user.click(checkbox3);
expect(validateSpy.mock.lastCall?.[0]).toEqual(['one', 'three']);
checkboxes.forEach((checkbox) => expect(checkbox).not.toHaveAttribute('aria-invalid'));
});
it('prop: validationMode=onChange', async () => {
const validateSpy = vi.fn((value) => {
const v = value as string[];
return v.includes('one') ? 'error' : null;
});
render(
<Field.Root validationMode="onChange" validate={validateSpy} name="apple">
<CheckboxGroup defaultValue={['one']}>
<Field.Item>
<Checkbox.Root value="one" data-testid="checkbox" />
</Field.Item>
<Field.Item>
<Checkbox.Root value="two" data-testid="checkbox" />
</Field.Item>
<Field.Item>
<Checkbox.Root value="three" data-testid="checkbox" />
</Field.Item>
</CheckboxGroup>
</Field.Root>,
);
const checkboxes = screen.getAllByTestId('checkbox');
const [checkbox1, checkbox2, checkbox3] = checkboxes;
checkboxes.forEach((checkbox) => expect(checkbox).not.toHaveAttribute('aria-invalid'));
fireEvent.click(checkbox1);
checkboxes.forEach((checkbox) => expect(checkbox).not.toHaveAttribute('aria-invalid'));
expect(validateSpy.mock.calls.length).toBe(1);
expect(validateSpy.mock.lastCall?.[0]).toEqual([]);
fireEvent.click(checkbox2);
checkboxes.forEach((checkbox) => expect(checkbox).not.toHaveAttribute('aria-invalid'));
expect(validateSpy.mock.calls.length).toBe(2);
expect(validateSpy.mock.lastCall?.[0]).toEqual(['two']);
fireEvent.click(checkbox1);
checkboxes.forEach((checkbox) => expect(checkbox).toHaveAttribute('aria-invalid', 'true'));
expect(validateSpy.mock.calls.length).toBe(3);
expect(validateSpy.mock.lastCall?.[0]).toEqual(['two', 'one']);
fireEvent.click(checkbox3);
checkboxes.forEach((checkbox) => expect(checkbox).toHaveAttribute('aria-invalid', 'true'));
});
it('validates with the group value when toggling the parent checkbox', async () => {
const validateSpy = vi.fn((_value: unknown) => null);
const { user } = render(
<Field.Root validationMode="onChange" validate={validateSpy} name="fruits">
<CheckboxGroup allValues={['apple', 'orange']}>
<Checkbox.Root parent data-testid="parent" />
<Checkbox.Root value="apple" />
<Checkbox.Root value="orange" />
</CheckboxGroup>
</Field.Root>,
);
const parent = screen.getByTestId('parent');
await user.click(parent);
expect(validateSpy).toHaveBeenCalledTimes(1);
expect(validateSpy.mock.lastCall?.[0]).toEqual(['apple', 'orange']);
await user.click(parent);
expect(validateSpy).toHaveBeenCalledTimes(2);
expect(validateSpy.mock.lastCall?.[0]).toEqual([]);
});
it('revalidates when the controlled value changes externally', async () => {
const validateSpy = vi.fn((value: unknown) => {
const values = value as string[];
return values.includes('one') ? 'error' : null;
});
function App() {
const [selected, setSelected] = React.useState<string[]>([]);
return (
<React.Fragment>
<Field.Root validationMode="onChange" validate={validateSpy} name="apple">
<CheckboxGroup value={selected}>
<Field.Item>
<Checkbox.Root value="one" data-testid="checkbox" />
</Field.Item>
<Field.Item>
<Checkbox.Root value="two" data-testid="checkbox" />
</Field.Item>
</CheckboxGroup>
</Field.Root>
<button type="button" onClick={() => setSelected(['one'])}>
Select externally
</button>
</React.Fragment>
);
}
render(<App />);
const checkboxes = screen.getAllByTestId('checkbox');
const toggle = screen.getByText('Select externally');
checkboxes.forEach((checkbox) => expect(checkbox).not.toHaveAttribute('aria-invalid'));
const initialCallCount = validateSpy.mock.calls.length;
fireEvent.click(toggle);
expect(validateSpy.mock.calls.length).toBe(initialCallCount + 1);
expect(validateSpy.mock.lastCall?.[0]).toEqual(['one']);
checkboxes.forEach((checkbox) => expect(checkbox).toHaveAttribute('aria-invalid', 'true'));
});
it('prop: validationMode=onBlur', async () => {
const validateSpy = vi.fn((value) => {
const v = value as string[];
return v.includes('one') ? 'error' : null;
});
render(
<Field.Root validationMode="onBlur" validate={validateSpy} name="apple">
<CheckboxGroup defaultValue={['one']}>
<Field.Item>
<Checkbox.Root value="one" data-testid="checkbox" />
</Field.Item>
<Field.Item>
<Checkbox.Root value="two" data-testid="checkbox" />
</Field.Item>
<Field.Item>
<Checkbox.Root value="three" data-testid="checkbox" />
</Field.Item>
</CheckboxGroup>
<Field.Error data-testid="error" />
</Field.Root>,
);
const checkboxes = screen.getAllByTestId('checkbox');
const [checkbox1, , checkbox3] = checkboxes;
checkboxes.forEach((checkbox) => expect(checkbox).not.toHaveAttribute('aria-invalid'));
fireEvent.click(checkbox1);
expect(validateSpy.mock.calls.length).toBe(0);
fireEvent.blur(checkbox1);
expect(validateSpy.mock.calls.length).toBe(1);
expect(validateSpy.mock.lastCall?.[0]).toEqual([]);
checkboxes.forEach((checkbox) => expect(checkbox).not.toHaveAttribute('aria-invalid'));
fireEvent.click(checkbox3);
expect(validateSpy.mock.calls.length).toBe(1);
fireEvent.blur(checkbox3);
expect(validateSpy.mock.calls.length).toBe(2);
expect(validateSpy.mock.lastCall?.[0]).toEqual(['three']);
checkboxes.forEach((checkbox) => expect(checkbox).not.toHaveAttribute('aria-invalid'));
fireEvent.click(checkbox1);
expect(validateSpy.mock.calls.length).toBe(2);
fireEvent.blur(checkbox1);
expect(validateSpy.mock.calls.length).toBe(3);
expect(validateSpy.mock.lastCall?.[0]).toEqual(['three', 'one']);
checkboxes.forEach((checkbox) => expect(checkbox).toHaveAttribute('aria-invalid', 'true'));
});
});
describe('Field.Label', () => {
it('implicit association', async () => {
const changeSpy = vi.fn();
render(
<Field.Root name="apple">
<CheckboxGroup defaultValue={['fuji-apple', 'gala-apple']}>
<Field.Item>
<Field.Label data-testid="label">
<Checkbox.Root value="fuji-apple" />
Fuji
</Field.Label>
</Field.Item>
<Field.Item>
<Field.Label data-testid="label">
<Checkbox.Root value="gala-apple" />
Gala
</Field.Label>
</Field.Item>
<Field.Item>
<Field.Label data-testid="label">
<Checkbox.Root value="granny-smith-apple" onCheckedChange={changeSpy} />
Granny Smith
</Field.Label>
</Field.Item>
</CheckboxGroup>
</Field.Root>,
);
const checkboxes = screen.getAllByRole('checkbox');
const labels = screen.getAllByTestId('label');
const inputs = document.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach((checkbox, index) => {
const label = labels[index];
const input = inputs[index];
expect(label.getAttribute('for')).not.toBe(null);
expect(label.getAttribute('for')).toBe(input.getAttribute('id'));
expect(label.getAttribute('id')).not.toBe(null);
expect(label.getAttribute('id')).toBe(checkbox.getAttribute('aria-labelledby'));
});
fireEvent.click(labels[2]);
expect(changeSpy.mock.calls.length).toBe(1);
});
it('explicit association', async () => {
const changeSpy = vi.fn();
await render(
<Field.Root name="apple">
<CheckboxGroup defaultValue={['fuji-apple', 'gala-apple']}>
<Field.Item>
<Checkbox.Root value="fuji-apple" />
<Field.Label data-testid="label">Fuji</Field.Label>
<Field.Description data-testid="description">
A fuji apple is the round, edible fruit of an apple tree
</Field.Description>
</Field.Item>
<Field.Item>
<Checkbox.Root value="gala-apple" onCheckedChange={changeSpy} />
<Field.Label data-testid="label">Gala</Field.Label>
<Field.Description data-testid="description">
A gala apple is the round, edible fruit of an apple tree
</Field.Description>
</Field.Item>
</CheckboxGroup>
</Field.Root>,
);
const checkboxes = screen.getAllByRole('checkbox');
const labels = screen.getAllByTestId('label');
const descriptions = screen.getAllByTestId('description');
const inputs = document.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach((checkbox, index) => {
const label = labels[index];
const description = descriptions[index];
const input = inputs[index];
expect(label.getAttribute('for')).not.toBe(null);
expect(label.getAttribute('for')).toBe(input.getAttribute('id'));
expect(label.getAttribute('id')).not.toBe(null);
expect(label.getAttribute('id')).toBe(checkbox.getAttribute('aria-labelledby'));
expect(description.getAttribute('id')).not.toBe(null);
expect(description.getAttribute('id')).toBe(checkbox.getAttribute('aria-describedby'));
});
fireEvent.click(screen.getByText('Gala'));
expect(changeSpy.mock.calls.length).toBe(1);
});
});
describe('Field.Description', () => {
it('links the group and individual checkboxes', async () => {
await render(
<Field.Root name="apple">
<CheckboxGroup defaultValue={[]} aria-describedby="external-description">
<Field.Description data-testid="group-description">Group description</Field.Description>
<Field.Item>
<Field.Label>
<Checkbox.Root value="fuji-apple" aria-describedby="checkbox-description" />
Fuji
</Field.Label>
</Field.Item>
</CheckboxGroup>
</Field.Root>,
);
const groupDescription = screen.getByTestId('group-description');
const groupDescriptionId = groupDescription.getAttribute('id');
expect(groupDescriptionId).not.toBe(null);
expect(screen.getByRole('group').getAttribute('aria-describedby')).toContain(
groupDescriptionId,
);
expect(screen.getByRole('checkbox').getAttribute('aria-describedby')).toContain(
groupDescriptionId,
);
expect(screen.getByRole('checkbox')).toHaveAttribute(
'aria-describedby',
`checkbox-description ${groupDescriptionId}`,
);
expect(screen.getByRole('group')).toHaveAttribute(
'aria-describedby',
`external-description ${groupDescriptionId}`,
);
});
});
describe('Form values', () => {
it('projects selected enabled checkboxes while preserving the logical validation value', () => {
const handleSubmit = vi.fn();
const validateGroup = vi.fn((_value: unknown, _formValues: Form.Values) => null);
const validateOther = vi.fn((_value: unknown, _formValues: Form.Values) => null);
function App() {
const [disabled, setDisabled] = React.useState(true);
return (
<Form onFormSubmit={handleSubmit} data-testid="form">
<Field.Root name="fruits" validate={validateGroup}>
<CheckboxGroup defaultValue={['apple', 'banana']}>
<Checkbox.Root value="apple" />
<Checkbox.Root value="banana" disabled={disabled} />
</CheckboxGroup>
</Field.Root>
<Field.Root name="other" validate={validateOther}>
<Field.Control defaultValue="value" />
</Field.Root>
<button type="button" onClick={() => setDisabled(false)}>
Enable
</button>
<button type="submit">Submit</button>