Skip to content
Source
Sign inSign up
TanStack/form
Open History to see the last commit

FormGroup.spec.tsx

641 lines17.8 KB

1import { describe, expect, it, vi } from 'vitest'
2import { render } from 'vitest-browser-preact'
3import { userEvent } from 'vitest/browser'
4import { useState } from 'preact/hooks'
5import { z } from 'zod'
6import { createFormHook, getFormHookHelpers, useForm } from '../src'
7import type { AnyInternalFormApi } from '@tanstack/form-core/internals'
8import type { FieldWithValue } from '@tanstack/form-core'
9​
10function FieldNameComp(props: { field: FieldWithValue<string> }) {
11 return <span data-testid="app-field-name">{props.field.name}</span>
13​
14function TextFieldComp(props: {
15 field: FieldWithValue<string>
16 label: string
17}) {
18 return (
19 <label>
20 {props.label}
21 <input
22 value={props.field.value}
23 onChange={(event) =>
24 props.field.handleChange(event.currentTarget.value)
25 }
26 onBlur={props.field.handleBlur}
27 />
28 <span data-testid="visible-errors">
29 {props.field.errors.map((error) => error.message).join(',')}
30 </span>
31 </label>
32 )
34​
35const { fieldComponent } = getFormHookHelpers()
36​
37const FieldName = fieldComponent.loose(FieldNameComp, 'field')
38const TextField = fieldComponent.strict(TextFieldComp, 'field')
39​
40const { useAppForm } = createFormHook({
41 fieldComponents: {
42 FieldName,
43 TextField,
44 },
45 formComponents: {},
46})
47​
48describe('FormGroup', () => {
49 it('renders from the normal form API and prefixes field names', async () => {
50 function Component() {
51 const form = useForm({
52 defaultValues: { guestDetails: { name: 'Tony' } },
53 })
54​
55 return (
56 <form.FormGroup name="guestDetails">
57 {(group) => (
58 <group.Field name="name">
59 {(field) => (
60 <span data-testid="field">
61 {field.name}:{field.value}
62 </span>
63 )}
64 </group.Field>
65 )}
66 </form.FormGroup>
67 )
68 }
69​
70 const { getByTestId } = render(<Component />)
71​
72 await expect
73 .element(getByTestId('field'))
74 .toHaveTextContent('guestDetails.name:Tony')
75 })
76​
77 it('prefixes array field names', async () => {
78 function Component() {
79 const form = useForm({
80 defaultValues: { guestDetails: { guests: ['Tony'] } },
81 })
82​
83 return (
84 <form.FormGroup name="guestDetails">
85 {(group) => (
86 <group.ArrayField name="guests">
87 {(field) => <span data-testid="array">{field.name}</span>}
88 </group.ArrayField>
89 )}
90 </form.FormGroup>
91 )
92 }
93​
94 const { getByTestId } = render(<Component />)
95​
96 await expect
97 .element(getByTestId('array'))
98 .toHaveTextContent('guestDetails.guests')
99 })
100​
101 it('provides AppForm field context for group fields', async () => {
102 function Component() {
103 const form = useAppForm({
104 defaultValues: { guestDetails: { name: 'Tony' } },
105 })
106​
107 return (
108 <form.AppForm>
109 <form.FormGroup name="guestDetails">
110 {(group) => (
111 <group.Field name="name">
112 {(field) => <field.FieldName />}
113 </group.Field>
114 )}
115 </form.FormGroup>
116 </form.AppForm>
117 )
118 }
119​
120 const { getByTestId } = render(<Component />)
121​
122 await expect
123 .element(getByTestId('app-field-name'))
124 .toHaveTextContent('guestDetails.name')
125 })
126​
127 it('uses the AppForm field provider subscription for field context', async () => {
128 const subscribe = vi.fn()
129 const unsubscribe = vi.fn()
130 const instrumentedAtoms = new WeakSet<object>()
131​
132 function Component() {
133 const form = useAppForm({
134 defaultValues: { guestDetails: { name: 'Tony' } },
135 })
136​
137 return (
138 <form.AppForm>
139 <form.FormGroup name="guestDetails">
140 {(group) => (
141 <group.Field name="name">
142 {(field) => {
143 const atom = field.atom
144 if (!instrumentedAtoms.has(atom)) {
145 instrumentedAtoms.add(atom)
146 const originalSubscribe = atom.subscribe as (
147 ...args: Array<any>
148 ) => ReturnType<typeof atom.subscribe>
149 atom.subscribe = (...args) => {
150 subscribe()
151 const subscription = originalSubscribe(...args)
152 let isActive = true
153 return {
154 unsubscribe: () => {
155 if (isActive) {
156 isActive = false
157 unsubscribe()
158 }
159 subscription.unsubscribe()
160 },
161 }
162 }
163 }
164​
165 return <field.FieldName />
166 }}
167 </group.Field>
168 )}
169 </form.FormGroup>
170 </form.AppForm>
171 )
172 }
173​
174 const { unmount } = render(<Component />)
175​
176 await vi.waitFor(() => {
177 expect(subscribe.mock.calls.length - unsubscribe.mock.calls.length).toBe(
178 2,
179 )
180 })
181​
182 unmount()
183​
184 await vi.waitFor(() => {
185 expect(subscribe.mock.calls.length - unsubscribe.mock.calls.length).toBe(
186 0,
187 )
188 })
189 })
190​
191 it('prefixes watched field names in group field listeners', async () => {
192 const listener = vi.fn()
193​
194 function Component() {
195 const form = useForm({
196 defaultValues: { guestDetails: { name: '', confirmation: '' } },
197 })
198​
199 return (
200 <form.FormGroup name="guestDetails">
201 {(group) => (
202 <>
203 <group.Field name="name">
204 {(field) => (
205 <input
206 aria-label="Guest name"
207 value={field.value}
208 onChange={(event) =>
209 field.handleChange(event.currentTarget.value)
210 }
211 />
212 )}
213 </group.Field>
214 <group.Field
215 name="confirmation"
216 listeners={[
217 {
218 triggers: ['change'],
219 watchFields: ['name'],
220 run: listener,
221 },
222 ]}
223 >
224 {() => null}
225 </group.Field>
226 </>
227 )}
228 </form.FormGroup>
229 )
230 }
231​
232 const { getByLabelText } = render(<Component />)
233​
234 await userEvent.type(getByLabelText('Guest name'), 'A')
235​
236 expect(listener).toHaveBeenCalledOnce()
237 })
238​
239 it('routes descendant field changes to the nearest form group', async () => {
240 const validator = vi.fn(() => ({
241 fields: {
242 name: 'Name is invalid',
243 },
244 }))
245​
246 function Component() {
247 const form = useForm({
248 defaultValues: { step1: { name: '' } },
249 })
250​
251 return (
252 <form.FormGroup
253 name="step1"
254 validators={[
255 {
256 triggers: ['change'],
257 run: validator,
258 },
259 ]}
260 >
261 {(group) => (
262 <group.Field name="name">
263 {(field) => (
264 <>
265 <input
266 aria-label="Step 1 name"
267 value={field.value}
268 onChange={(event) =>
269 field.handleChange(event.currentTarget.value)
270 }
271 />
272 <span data-testid="change-error">
273 {field.errors.map((error) => error.message).join(',')}
274 </span>
275 </>
276 )}
277 </group.Field>
278 )}
279 </form.FormGroup>
280 )
281 }
282​
283 const { getByLabelText, getByTestId } = render(<Component />)
284​
285 await userEvent.type(getByLabelText('Step 1 name'), 'A')
286​
287 await vi.waitFor(() => {
288 expect(validator).toHaveBeenCalledOnce()
289 })
290 await expect
291 .element(getByTestId('change-error'))
292 .toHaveTextContent('Name is invalid')
293 })
294​
295 it('subscribes to group state updates and advances an external stepper on submit', async () => {
296 function Component() {
297 const [step, setStep] = useState(0)
298 const form = useForm({
299 defaultValues: { guestDetails: { name: 'Tony' } },
300 })
301​
302 return (
303 <>
304 <span data-testid="step">{step}</span>
305 <form.FormGroup
306 name="guestDetails"
307 onSubmit={() => setStep((prev) => prev + 1)}
308 >
309 {(group) => (
310 <>
311 <group.Subscribe selector={(state) => state.submissionAttempts}>
312 {(attempts) => <span data-testid="attempts">{attempts}</span>}
313 </group.Subscribe>
314 <button onClick={() => group.handleSubmit()}>Continue</button>
315 </>
316 )}
317 </form.FormGroup>
318 </>
319 )
320 }
321​
322 const { getByText, getByTestId } = render(<Component />)
323​
324 await userEvent.click(getByText('Continue'))
325​
326 await expect.element(getByTestId('step')).toHaveTextContent('1')
327 await expect.element(getByTestId('attempts')).toHaveTextContent('1')
328 })
329​
330 it('renders descendant field errors on invalid group submit', async () => {
331 function Component() {
332 const form = useForm({
333 defaultValues: { guestDetails: { name: '' } },
334 })
335​
336 return (
337 <form.FormGroup name="guestDetails">
338 {(group) => (
339 <>
340 <group.Field
341 name="name"
342 validators={[
343 {
344 triggers: [],
345 run: () => 'Name is required',
346 },
347 ]}
348 >
349 {(field) => (
350 <span data-testid="error">
351 {field.errors.map((error) => error.message).join(',')}
352 </span>
353 )}
354 </group.Field>
355 <button onClick={() => group.handleSubmit()}>Continue</button>
356 </>
357 )}
358 </form.FormGroup>
359 )
360 }
361​
362 const { getByText, getByTestId } = render(<Component />)
363​
364 await userEvent.click(getByText('Continue'))
365​
366 await expect
367 .element(getByTestId('error'))
368 .toHaveTextContent('Name is required')
369 })
370​
371 it('routes group validator field errors to prefixed group fields', async () => {
372 function Component() {
373 const form = useForm({
374 defaultValues: { step1: { name: '' } },
375 })
376​
377 return (
378 <form.FormGroup
379 name="step1"
380 validators={[
381 {
382 triggers: [],
383 run: () => ({
384 fields: {
385 name: 'Name is required',
386 },
387 }),
388 },
389 ]}
390 >
391 {(group) => (
392 <>
393 <group.Field name="name">
394 {(field) => (
395 <span data-testid="group-field-error">
396 {field.name}:
397 {field.errors.map((error) => error.message).join(',')}
398 </span>
399 )}
400 </group.Field>
401 <button onClick={() => group.handleSubmit()}>Continue</button>
402 </>
403 )}
404 </form.FormGroup>
405 )
406 }
407​
408 const { getByText, getByTestId } = render(<Component />)
409​
410 await userEvent.click(getByText('Continue'))
411​
412 await expect
413 .element(getByTestId('group-field-error'))
414 .toHaveTextContent('step1.name:Name is required')
415 })
416​
417 it('renders Standard Schema group errors through AppForm field components', async () => {
418 const formRef = { current: null as AnyInternalFormApi | null }
419 const step1Schema = z.object({
420 name: z.string().min(2, 'Name must be at least 2 characters'),
421 })
422 const validate = vi.spyOn(step1Schema['~standard'], 'validate')
423​
424 function Component() {
425 const form = useAppForm({
426 defaultValues: { step1: { name: '' } },
427 })
428 formRef.current = form as never
429​
430 return (
431 <form.AppForm>
432 <form.FormGroup
433 name="step1"
434 validators={[
435 {
436 triggers: [],
437 run: step1Schema,
438 },
439 ]}
440 >
441 {(group) => (
442 <form
443 onSubmit={(event) => {
444 event.preventDefault()
445 event.stopPropagation()
446 group.handleSubmit()
447 }}
448 >
449 <group.Field name="name">
450 {(field) => <field.TextField label="Step 1 Name" />}
451 </group.Field>
452 <button type="submit">Submit</button>
453 </form>
454 )}
455 </form.FormGroup>
456 </form.AppForm>
457 )
458 }
459​
460 const { getByText, getByTestId } = render(<Component />)
461​
462 await userEvent.click(getByText('Submit'))
463​
464 await vi.waitFor(() => {
465 expect(validate).toHaveBeenCalled()
466 expect(
467 formRef.current?._tryGetFieldApi('step1.name')?.meta.original.errors,
468 ).toEqual([
469 expect.objectContaining({
470 message: 'Name must be at least 2 characters',
471 }),
472 ])
473 })
474 await expect
475 .element(getByTestId('visible-errors'))
476 .toHaveTextContent('Name must be at least 2 characters')
477 })
478​
479 it('routes descendant Standard Schema group errors to an error boundary field', async () => {
480 const stayDatesSchema = z.object({
481 dateRange: z.object({
482 from: z
483 .date()
484 .optional()
485 .refine(
486 (value) => value !== undefined,
487 'Please select a start date.',
488 ),
489 to: z
490 .date()
491 .optional()
492 .refine((value) => value !== undefined, 'Please select an end date.'),
493 }),
494 arrivalTime: z.string().min(1, 'Please select an arrival time.'),
495 })
496 type StayDates = z.input<typeof stayDatesSchema>
497 const defaultValues: { stayDates: StayDates } = {
498 stayDates: {
499 dateRange: {
500 from: undefined,
501 to: undefined,
502 },
503 arrivalTime: '',
504 },
505 }
506​
507 function Component() {
508 const form = useForm({
509 defaultValues,
510 })
511​
512 return (
513 <form.FormGroup
514 name="stayDates"
515 validators={[
516 {
517 triggers: [],
518 run: stayDatesSchema,
519 },
520 ]}
521 >
522 {(group) => (
523 <>
524 <group.Field name="dateRange" errorBoundary>
525 {(field) => (
526 <span data-testid="date-range-errors">
527 {field.errors.map((error) => error.message).join(',')}
528 </span>
529 )}
530 </group.Field>
531 <group.Field name="arrivalTime">
532 {(field) => (
533 <span data-testid="arrival-time-errors">
534 {field.errors.map((error) => error.message).join(',')}
535 </span>
536 )}
537 </group.Field>
538 <button onClick={() => group.handleSubmit()}>Continue</button>
539 </>
540 )}
541 </form.FormGroup>
542 )
543 }
544​
545 const { getByText, getByTestId } = render(<Component />)
546​
547 await userEvent.click(getByText('Continue'))
548​
549 await expect
550 .element(getByTestId('arrival-time-errors'))
551 .toHaveTextContent('Please select an arrival time.')
552 await expect
553 .element(getByTestId('date-range-errors'))
554 .toHaveTextContent(
555 'Please select a start date.,Please select an end date.',
556 )
557 })
558​
559 it('does not add a DOM-rendering StepForm helper', async () => {
560 function Component() {
561 const form = useForm({ defaultValues: { guestDetails: { name: '' } } })
562 return <span data-testid="exists">{String('StepForm' in form)}</span>
563 }
564​
565 const { getByTestId } = render(<Component />)
566​
567 await expect.element(getByTestId('exists')).toHaveTextContent('false')
568 })
569​
570 it('clears group-routed errors on unmount without resetting values', async () => {
571 const formRef = { current: null as AnyInternalFormApi | null }
572​
573 function Component() {
574 const [showGroup, setShowGroup] = useState(true)
575 const form = useForm({
576 defaultValues: { guestDetails: { name: '' } },
577 })
578 formRef.current = form as never
579​
580 return (
581 <>
582 {showGroup && (
583 <form.FormGroup
584 name="guestDetails"
585 validators={[
586 {
587 triggers: [],
588 run: () => ({
589 fields: {
590 name: 'Name is required',
591 },
592 }),
593 },
594 ]}
595 >
596 {(group) => (
597 <button onClick={() => group.handleSubmit()}>Continue</button>
598 )}
599 </form.FormGroup>
600 )}
601 <form.Field name="guestDetails.name">
602 {(field) => (
603 <>
604 <input
605 aria-label="Guest name"
606 value={field.value}
607 onChange={(event) =>
608 field.handleChange(event.currentTarget.value)
609 }
610 />
611 <span data-testid="error">
612 {field.errors.map((error) => error.message).join(',')}
613 </span>
614 </>
615 )}
616 </form.Field>
617 <button onClick={() => setShowGroup(false)}>Unmount group</button>
618 </>
619 )
620 }
621​
622 const { getByLabelText, getByText, getByTestId } = render(<Component />)
623 const input = getByLabelText('Guest name')
624​
625 await userEvent.type(input, 'Preserved')
626 await userEvent.clear(input)
627 await userEvent.click(getByText('Continue'))
628​
629 await expect
630 .element(getByTestId('error'))
631 .toHaveTextContent('Name is required')
632​
633 await userEvent.type(input, 'Still here')
634 await userEvent.click(getByText('Unmount group'))
635​
636 await expect.element(getByTestId('error')).toHaveTextContent('')
637 expect(formRef.current?.state.values).toEqual({
638 guestDetails: { name: 'Still here' },
639 })
640 })
641})