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