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

createFormHook.test.tsx

761 lines18.7 KB

1import { describe, expect, it } from 'vitest'
2import { render, waitFor } from '@testing-library/react'
3import { formOptions } from '@tanstack/form-core'
4import userEvent from '@testing-library/user-event'
5import { createFormHook, createFormHookContexts, useStore } from '../src'
6​
7const user = userEvent.setup()
8​
9const { fieldContext, useFieldContext, formContext, useFormContext } =
10 createFormHookContexts()
11​
12function TextField({ label }: { label: string }) {
13 const field = useFieldContext<string>()
14 return (
15 <label>
16 <div>{label}</div>
17 <input
18 value={field.state.value}
19 onChange={(e) => field.handleChange(e.target.value)}
20 />
21 </label>
22 )
24​
25function SubscribeButton({ label }: { label: string }) {
26 const form = useFormContext()
27 return (
28 <form.Subscribe selector={(state) => state.isSubmitting}>
29 {(isSubmitting) => <button disabled={isSubmitting}>{label}</button>}
30 </form.Subscribe>
31 )
33​
34const { useAppForm, withForm, withFieldGroup, useTypedAppFormContext } =
35 createFormHook({
36 fieldComponents: {
37 TextField,
38 },
39 formComponents: {
40 SubscribeButton,
41 },
42 fieldContext,
43 formContext,
44 })
45​
46describe('createFormHook', () => {
47 it('should allow to set default value', () => {
48 type Person = {
49 firstName: string
50 lastName: string
51 }
52​
53 function Comp() {
54 const form = useAppForm({
55 defaultValues: {
56 firstName: 'FirstName',
57 lastName: 'LastName',
58 } as Person,
59 })
60​
61 return (
62 <>
63 <form.AppField
64 name="firstName"
65 children={(field) => <field.TextField label="Testing" />}
66 />
67 </>
68 )
69 }
70​
71 const { getByLabelText } = render(<Comp />)
72 const input = getByLabelText('Testing')
73 expect(input).toHaveValue('FirstName')
74 })
75​
76 it('should handle withForm types properly', () => {
77 const formOpts = formOptions({
78 defaultValues: {
79 firstName: 'John',
80 lastName: 'Doe',
81 },
82 })
83​
84 const ChildForm = withForm({
85 ...formOpts,
86 // Optional, but adds props to the `render` function outside of `form`
87 props: {
88 title: 'Child Form',
89 },
90 render: ({ form, title }) => {
91 return (
92 <div>
93 <p>{title}</p>
94 <form.AppField
95 name="firstName"
96 children={(field) => <field.TextField label="First Name" />}
97 />
98 <form.AppForm>
99 <form.SubscribeButton label="Submit" />
100 </form.AppForm>
101 </div>
102 )
103 },
104 })
105​
106 const Parent = () => {
107 const form = useAppForm({
108 ...formOpts,
109 })
110​
111 return <ChildForm form={form} title={'Testing'} />
112 }
113​
114 const { getByLabelText, getByText } = render(<Parent />)
115 const input = getByLabelText('First Name')
116 expect(input).toHaveValue('John')
117 expect(getByText('Testing')).toBeInTheDocument()
118 })
119​
120 it('should handle withFieldGroup types properly', () => {
121 const formOpts = formOptions({
122 defaultValues: {
123 person: {
124 firstName: 'John',
125 lastName: 'Doe',
126 },
127 },
128 })
129​
130 const ChildForm = withFieldGroup({
131 defaultValues: formOpts.defaultValues.person,
132 // Optional, but adds props to the `render` function outside of `form`
133 props: {
134 title: 'Child Form',
135 },
136 render: ({ group, title }) => {
137 return (
138 <div>
139 <p>{title}</p>
140 <group.AppField
141 name="firstName"
142 children={(field) => <field.TextField label="First Name" />}
143 />
144 <group.AppForm>
145 <group.SubscribeButton label="Submit" />
146 </group.AppForm>
147 </div>
148 )
149 },
150 })
151​
152 const Parent = () => {
153 const form = useAppForm({
154 ...formOpts,
155 })
156​
157 return <ChildForm form={form} fields="person" title={'Testing'} />
158 }
159​
160 const { getByLabelText, getByText } = render(<Parent />)
161 const input = getByLabelText('First Name')
162 expect(input).toHaveValue('John')
163 expect(getByText('Testing')).toBeInTheDocument()
164 })
165​
166 it('should use the correct field name in Field with withFieldGroup', () => {
167 const formOpts = formOptions({
168 defaultValues: {
169 person: {
170 firstName: 'John',
171 lastName: 'Doe',
172 },
173 people: [
174 {
175 firstName: 'Jane',
176 lastName: 'Doe',
177 },
178 {
179 firstName: 'Robert',
180 lastName: 'Doe',
181 },
182 ],
183 },
184 })
185​
186 const ChildFormAsField = withFieldGroup({
187 defaultValues: formOpts.defaultValues.person,
188 render: ({ group }) => {
189 return (
190 <div>
191 <group.AppField
192 name="firstName"
193 children={(field) => <field.TextField label={field.name} />}
194 />
195 <group.AppForm>
196 <group.SubscribeButton label="Submit" />
197 </group.AppForm>
198 </div>
199 )
200 },
201 })
202 const ChildFormAsArray = withFieldGroup({
203 defaultValues: [formOpts.defaultValues.person],
204 props: {
205 title: '',
206 },
207 render: ({ group, title }) => {
208 return (
209 <div>
210 <p>{title}</p>
211 <group.AppField
212 name="[0].firstName"
213 children={(field) => <field.TextField label={field.name} />}
214 />
215 <group.AppForm>
216 <group.SubscribeButton label="Submit" />
217 </group.AppForm>
218 </div>
219 )
220 },
221 })
222​
223 const Parent = () => {
224 const form = useAppForm({
225 ...formOpts,
226 })
227​
228 return (
229 <>
230 <ChildFormAsField form={form} fields="person" />
231 <ChildFormAsArray form={form} fields="people" title="Testing" />
232 <ChildFormAsField form={form} fields="people[1]" />
233 </>
234 )
235 }
236​
237 const { getByLabelText, getByText } = render(<Parent />)
238 const inputField1 = getByLabelText('person.firstName')
239 const inputArray = getByLabelText('people[0].firstName')
240 const inputField2 = getByLabelText('people[1].firstName')
241 expect(inputField1).toHaveValue('John')
242 expect(inputArray).toHaveValue('Jane')
243 expect(inputField2).toHaveValue('Robert')
244 expect(getByText('Testing')).toBeInTheDocument()
245 })
246​
247 it('should forward Field and Subscribe to the form', () => {
248 const formOpts = formOptions({
249 defaultValues: {
250 person: {
251 firstName: 'John',
252 lastName: 'Doe',
253 },
254 },
255 })
256​
257 const ChildFormAsField = withFieldGroup({
258 defaultValues: formOpts.defaultValues.person,
259 render: ({ group }) => {
260 return (
261 <div>
262 <group.Field
263 name="firstName"
264 children={(field) => (
265 <label>
266 <div>{field.name}</div>
267 <input
268 value={field.state.value}
269 onChange={(e) => field.handleChange(e.target.value)}
270 />
271 </label>
272 )}
273 />
274 <group.Subscribe selector={(state) => state.values.lastName}>
275 {(lastName) => <p>{lastName}</p>}
276 </group.Subscribe>
277 </div>
278 )
279 },
280 })
281​
282 const Parent = () => {
283 const form = useAppForm({
284 ...formOpts,
285 })
286 return <ChildFormAsField form={form} fields="person" />
287 }
288​
289 const { getByLabelText, getByText } = render(<Parent />)
290 const input = getByLabelText('person.firstName')
291 expect(input).toHaveValue('John')
292 expect(getByText('Doe')).toBeInTheDocument()
293 })
294​
295 it('should not lose focus on update with withFieldGroup', async () => {
296 const formOpts = formOptions({
297 defaultValues: {
298 person: {
299 firstName: 'John',
300 lastName: 'Doe',
301 },
302 },
303 })
304​
305 const ChildForm = withFieldGroup({
306 defaultValues: formOpts.defaultValues.person,
307 render: function Render({ group }) {
308 const firstName = useStore(
309 group.store,
310 (state) => state.values.firstName,
311 )
312 return (
313 <div>
314 <p>{firstName}</p>
315 <group.Field
316 name="firstName"
317 children={(field) => (
318 <label>
319 <div>{field.name}</div>
320 <input
321 value={field.state.value}
322 onChange={(e) => field.handleChange(e.target.value)}
323 />
324 </label>
325 )}
326 />
327 <group.Subscribe selector={(state) => state.values.lastName}>
328 {(lastName) => <p>{lastName}</p>}
329 </group.Subscribe>
330 </div>
331 )
332 },
333 })
334​
335 const Parent = () => {
336 const form = useAppForm({
337 ...formOpts,
338 })
339 return <ChildForm form={form} fields="person" />
340 }
341​
342 const { getByLabelText } = render(<Parent />)
343​
344 const input = getByLabelText('person.firstName')
345 input.focus()
346 expect(input).toHaveFocus()
347​
348 await user.clear(input)
349 await user.type(input, 'Something')
350​
351 expect(input).toHaveFocus()
352 })
353​
354 it('should allow nesting withFieldGroup in other withFieldGroups', () => {
355 type Nested = {
356 firstName: string
357 }
358 type Wrapper = {
359 field: Nested
360 }
361 type FormValues = {
362 form: Wrapper
363 unrelated: { something: { lastName: string } }
364 }
365​
366 const defaultValues: FormValues = {
367 form: {
368 field: {
369 firstName: 'Test',
370 },
371 },
372 unrelated: {
373 something: {
374 lastName: '',
375 },
376 },
377 }
378​
379 const LensNested = withFieldGroup({
380 defaultValues: defaultValues.form.field,
381 render: function Render({ group }) {
382 return (
383 <group.Field name="firstName">
384 {(field) => <p>{field.name}</p>}
385 </group.Field>
386 )
387 },
388 })
389 const LensWrapper = withFieldGroup({
390 defaultValues: defaultValues.form,
391 render: function Render({ group }) {
392 return (
393 <div>
394 <LensNested form={group} fields="field" />
395 </div>
396 )
397 },
398 })
399​
400 const Parent = () => {
401 const form = useAppForm({
402 defaultValues,
403 })
404 return <LensWrapper form={form} fields="form" />
405 }
406​
407 const { getByText } = render(<Parent />)
408​
409 expect(getByText('form.field.firstName')).toBeInTheDocument()
410 })
411​
412 it('should allow mapping withFieldGroup to different values', () => {
413 const formOpts = formOptions({
414 defaultValues: {
415 unrelated: 'John',
416 values: '',
417 },
418 })
419​
420 const ChildFormAsField = withFieldGroup({
421 defaultValues: { firstName: '', lastName: '' },
422 render: ({ group }) => {
423 return (
424 <div>
425 <group.AppField
426 name="firstName"
427 children={(field) => <field.TextField label={field.name} />}
428 />
429 </div>
430 )
431 },
432 })
433​
434 const Parent = () => {
435 const form = useAppForm({
436 ...formOpts,
437 })
438​
439 return (
440 <ChildFormAsField
441 form={form}
442 fields={{
443 firstName: 'unrelated',
444 lastName: 'values',
445 }}
446 />
447 )
448 }
449​
450 const { getByLabelText } = render(<Parent />)
451 const inputField1 = getByLabelText('unrelated')
452 expect(inputField1).toHaveValue('John')
453 })
454​
455 it('should remap FieldGroupApi.Field validators to the correct names', () => {
456 const FieldGroupString = withFieldGroup({
457 defaultValues: { password: '', confirmPassword: '' },
458 render: function Render({ group }) {
459 return (
460 <group.Field
461 name="password"
462 validators={{
463 onChange: () => null,
464 onChangeListenTo: ['password'],
465 onBlur: () => null,
466 onBlurListenTo: ['confirmPassword'],
467 }}
468 >
469 {(field) => {
470 expect(field.options.validators?.onChangeListenTo).toStrictEqual([
471 'account.password',
472 ])
473 expect(field.options.validators?.onBlurListenTo).toStrictEqual([
474 'account.confirmPassword',
475 ])
476 return <></>
477 }}
478 </group.Field>
479 )
480 },
481 })
482​
483 const FieldGroupObject = withFieldGroup({
484 defaultValues: { password: '', confirmPassword: '' },
485 render: function Render({ group }) {
486 return (
487 <group.Field
488 name="password"
489 validators={{
490 onChange: () => null,
491 onChangeListenTo: ['password'],
492 onBlur: () => null,
493 onBlurListenTo: ['confirmPassword'],
494 }}
495 >
496 {(field) => {
497 expect(field.options.validators?.onChangeListenTo).toStrictEqual([
498 'userPassword',
499 ])
500 expect(field.options.validators?.onBlurListenTo).toStrictEqual([
501 'userConfirmPassword',
502 ])
503 return <></>
504 }}
505 </group.Field>
506 )
507 },
508 })
509​
510 const Parent = () => {
511 const form = useAppForm({
512 defaultValues: {
513 account: {
514 password: '',
515 confirmPassword: '',
516 },
517 userPassword: '',
518 userConfirmPassword: '',
519 },
520 })
521​
522 return (
523 <>
524 <FieldGroupString form={form} fields="account" />
525 <FieldGroupObject
526 form={form}
527 fields={{
528 password: 'userPassword',
529 confirmPassword: 'userConfirmPassword',
530 }}
531 />
532 </>
533 )
534 }
535​
536 render(<Parent />)
537 })
538​
539 it('should accept formId and return it', async () => {
540 function Submit() {
541 const form = useFormContext()
542​
543 return (
544 <button type="submit" form={form.formId} data-testid="formId-target">
545 {form.formId}
546 </button>
547 )
548 }
549​
550 function Comp() {
551 const form = useAppForm({
552 formId: 'test',
553 })
554​
555 return (
556 <form.AppForm>
557 <form
558 id={form.formId}
559 onSubmit={(e) => {
560 e.preventDefault()
561 form.handleSubmit()
562 }}
563 ></form>
564​
565 <form.Subscribe
566 selector={(state) => state.submissionAttempts}
567 children={(submissionAttempts) => (
568 <span data-testid="formId-result">{submissionAttempts}</span>
569 )}
570 />
571​
572 <Submit />
573 </form.AppForm>
574 )
575 }
576​
577 const { getByTestId } = render(<Comp />)
578 const target = getByTestId('formId-target')
579 const result = getByTestId('formId-result')
580​
581 await user.click(target)
582 expect(result).toHaveTextContent('1')
583 })
584​
585 it('should allow using typed app form', () => {
586 type Person = {
587 firstName: string
588 lastName: string
589 }
590 const formOpts = formOptions({
591 defaultValues: {
592 firstName: 'FirstName',
593 lastName: 'LastName',
594 } as Person,
595 })
596​
597 function Child() {
598 const form = useTypedAppFormContext(formOpts)
599​
600 return (
601 <form.AppField
602 name="firstName"
603 children={(field) => <field.TextField label="Testing" />}
604 />
605 )
606 }
607​
608 function Parent() {
609 const form = useAppForm({
610 defaultValues: {
611 firstName: 'FirstName',
612 lastName: 'LastName',
613 } as Person,
614 })
615​
616 return (
617 <form.AppForm>
618 <Child />
619 </form.AppForm>
620 )
621 }
622​
623 const { getByLabelText } = render(<Parent />)
624 const input = getByLabelText('Testing')
625 expect(input).toHaveValue('FirstName')
626 })
627​
628 it('should throw if `useTypedAppFormContext` is used without AppForm', () => {
629 type Person = {
630 firstName: string
631 lastName: string
632 }
633 const formOpts = formOptions({
634 defaultValues: {
635 firstName: 'FirstName',
636 lastName: 'LastName',
637 } as Person,
638 })
639​
640 function Child() {
641 const form = useTypedAppFormContext(formOpts)
642​
643 return (
644 <form.AppField
645 name="firstName"
646 children={(field) => <field.TextField label="Testing" />}
647 />
648 )
649 }
650​
651 function Parent() {
652 const form = useAppForm({
653 defaultValues: {
654 firstName: 'FirstName',
655 lastName: 'LastName',
656 } as Person,
657 })
658​
659 return <Child />
660 }
661​
662 expect(() => render(<Parent />)).toThrow()
663 })
664​
665 it('should allow using typed app form with form components', () => {
666 type Person = {
667 firstName: string
668 lastName: string
669 }
670 const formOpts = formOptions({
671 defaultValues: {
672 firstName: 'FirstName',
673 lastName: 'LastName',
674 } as Person,
675 })
676​
677 function Child() {
678 const form = useTypedAppFormContext(formOpts)
679​
680 return <form.SubscribeButton label="Testing" />
681 }
682​
683 function Parent() {
684 const form = useAppForm({
685 defaultValues: {
686 firstName: 'FirstName',
687 lastName: 'LastName',
688 } as Person,
689 })
690​
691 return (
692 <form.AppForm>
693 <Child />
694 </form.AppForm>
695 )
696 }
697​
698 const { getByText } = render(<Parent />)
699 const button = getByText('Testing')
700 expect(button).toBeInTheDocument()
701 })
702​
703 it('should render FieldGroup Subscribe without selector (default identity)', async () => {
704 const formOpts = formOptions({
705 defaultValues: {
706 person: {
707 firstName: 'FirstName',
708 lastName: 'LastName',
709 },
710 },
711 })
712​
713 const ChildFormAsField = withFieldGroup({
714 defaultValues: formOpts.defaultValues.person,
715 render: ({ group }) => {
716 return (
717 <div>
718 <group.Field
719 name="lastName"
720 children={(field) => (
721 <label>
722 Last Name:
723 <input
724 data-testid="lastName"
725 value={field.state.value}
726 onBlur={field.handleBlur}
727 onChange={(e) => field.handleChange(e.target.value)}
728 />
729 </label>
730 )}
731 />
732 <group.Subscribe
733 children={(state) => (
734 <span data-testid="state-lastName">
735 {state.values.lastName}
736 </span>
737 )}
738 />
739 </div>
740 )
741 },
742 })
743​
744 const Parent = () => {
745 const form = useAppForm({
746 ...formOpts,
747 })
748 return <ChildFormAsField form={form} fields="person" />
749 }
750​
751 const { getByTestId } = render(<Parent />)
752 const input = getByTestId('lastName')
753 const stateLastName = getByTestId('state-lastName')
754​
755 expect(stateLastName).toHaveTextContent('LastName')
756​
757 await user.clear(input)
758 await user.type(input, 'Updated')
759 await waitFor(() => expect(stateLastName).toHaveTextContent('Updated'))
760 })
761})