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

createFormHook.test.tsx

707 lines18.4 KB

1import { describe, expect, it, vi } from 'vitest'
2import { render } from '@solidjs/testing-library'
3import { formOptions } from '@tanstack/form-core'
4import userEvent from '@testing-library/user-event'
5import { createEffect, createSignal } from 'solid-js'
6import { createFormHook, createFormHookContexts, useStore } from '../src'
7​
8const user = userEvent.setup()
9​
10const { fieldContext, useFieldContext, formContext, useFormContext } =
11 createFormHookContexts()
12​
13function TextField({ label }: { label: string }) {
14 const field = useFieldContext<string>()
15 return (
16 <label>
17 <div>{label}</div>
18 <input
19 value={field().state.value}
20 onChange={(e) => field().handleChange(e.target.value)}
21 />
22 </label>
23 )
25​
26function SubscribeButton({ label }: { label: string }) {
27 const form = useFormContext()
28 return (
29 <form.Subscribe selector={(state) => state.isSubmitting}>
30 {(isSubmitting) => <button disabled={isSubmitting()}>{label}</button>}
31 </form.Subscribe>
32 )
34​
35const { useAppForm, withForm, withFieldGroup } = 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(
471 field().options.validators?.onChangeListenTo,
472 ).toStrictEqual(['account.password'])
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(
498 field().options.validators?.onChangeListenTo,
499 ).toStrictEqual(['userPassword'])
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 keep props reactive in JSX when passed to withForm component', async () => {
540 const formOpts = formOptions({ defaultValues: { name: '' } })
541​
542 const StatusForm = withForm({
543 ...formOpts,
544 props: {
545 status: 'idle' as 'idle' | 'loading',
546 count: 0,
547 },
548 render: (props) => (
549 <div>
550 <span data-testid="status">{props.status}</span>
551 <span data-testid="count">{props.count}</span>
552 </div>
553 ),
554 })
555​
556 const Parent = () => {
557 const form = useAppForm(() => formOpts)
558 const [status, setStatus] = createSignal<'idle' | 'loading'>('idle')
559 const [count, setCount] = createSignal(0)
560 return (
561 <div>
562 <StatusForm form={form} status={status()} count={count()} />
563 <button data-testid="btn-status" onClick={() => setStatus('loading')}>
564 change
565 </button>
566 <button
567 data-testid="btn-count"
568 onClick={() => setCount((c) => c + 1)}
569 >
570 inc
571 </button>
572 </div>
573 )
574 }
575​
576 const { getByTestId } = render(() => <Parent />)
577​
578 expect(getByTestId('status')).toHaveTextContent('idle')
579 expect(getByTestId('count')).toHaveTextContent('0')
580​
581 await user.click(getByTestId('btn-status'))
582 expect(getByTestId('status')).toHaveTextContent('loading')
583​
584 await user.click(getByTestId('btn-count'))
585 expect(getByTestId('count')).toHaveTextContent('1')
586 })
587​
588 it('should re-run createEffect when reactive props change in withForm render', async () => {
589 const formOpts = formOptions({ defaultValues: { name: '' } })
590 const spy = vi.fn()
591​
592 const StatusForm = withForm({
593 ...formOpts,
594 props: { status: 'idle' as 'idle' | 'loading' },
595 render: (props) => {
596 createEffect(() => {
597 spy(props.status)
598 })
599 return <div data-testid="status">{props.status}</div>
600 },
601 })
602​
603 const Parent = () => {
604 const form = useAppForm(() => formOpts)
605 const [status, setStatus] = createSignal<'idle' | 'loading'>('idle')
606 return (
607 <div>
608 <StatusForm form={form} status={status()} />
609 <button data-testid="btn" onClick={() => setStatus('loading')}>
610 change
611 </button>
612 </div>
613 )
614 }
615​
616 const { getByTestId } = render(() => <Parent />)
617​
618 expect(spy).toHaveBeenCalledTimes(1)
619 expect(spy).toHaveBeenLastCalledWith('idle')
620​
621 await user.click(getByTestId('btn'))
622 expect(spy).toHaveBeenCalledTimes(2)
623 expect(spy).toHaveBeenLastCalledWith('loading')
624 })
625​
626 it('should keep props reactive in withFieldGroup component', async () => {
627 const formOpts = formOptions({
628 defaultValues: { person: { firstName: 'John' } },
629 })
630​
631 const PersonGroup = withFieldGroup({
632 defaultValues: formOpts.defaultValues.person,
633 props: { label: 'default' },
634 render: (props) => (
635 <div>
636 <span data-testid="label">{props.label}</span>
637 </div>
638 ),
639 })
640​
641 const Parent = () => {
642 const form = useAppForm(() => formOpts)
643 const [label, setLabel] = createSignal('initial')
644 return (
645 <div>
646 <PersonGroup form={form} fields="person" label={label()} />
647 <button data-testid="btn" onClick={() => setLabel('updated')}>
648 change
649 </button>
650 </div>
651 )
652 }
653​
654 const { getByTestId } = render(() => <Parent />)
655​
656 expect(getByTestId('label')).toHaveTextContent('initial')
657​
658 await user.click(getByTestId('btn'))
659 expect(getByTestId('label')).toHaveTextContent('updated')
660 })
661​
662 it('should accept formId and return it', async () => {
663 function Submit() {
664 const form = useFormContext()
665​
666 return (
667 <button type="submit" form={form.formId} data-testid="formId-target">
668 {form.formId}
669 </button>
670 )
671 }
672​
673 function Comp() {
674 const form = useAppForm(() => ({
675 formId: 'test',
676 }))
677​
678 return (
679 <form.AppForm>
680 <form
681 id={form.formId}
682 onSubmit={(e) => {
683 e.preventDefault()
684 form.handleSubmit()
685 }}
686 ></form>
687​
688 <form.Subscribe
689 selector={(state) => state.submissionAttempts}
690 children={(submissionAttempts) => (
691 <span data-testid="formId-result">{submissionAttempts()}</span>
692 )}
693 />
694​
695 <Submit />
696 </form.AppForm>
697 )
698 }
699​
700 const { getByTestId } = render(() => <Comp />)
701 const target = getByTestId('formId-target')
702 const result = getByTestId('formId-result')
703​
704 await user.click(target)
705 expect(result).toHaveTextContent('1')
706 })
707})