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

useForm.test.tsx

797 lines21.8 KB

1import { describe, expect, it, vi } from 'vitest'
2import { render, waitFor } from '@testing-library/react'
3import { userEvent } from '@testing-library/user-event'
4import { useStore } from '@tanstack/react-store'
5import { useEffect, useState } from 'react'
6import { useForm } from '../src/index'
7import { sleep } from './utils'
8​
9const user = userEvent.setup()
10​
11describe('useForm', () => {
12 it('preserves field state', async () => {
13 type Person = {
14 firstName: string
15 lastName: string
16 }
17​
18 function Comp() {
19 const form = useForm({
20 defaultValues: {} as Person,
21 })
22​
23 return (
24 <>
25 <form.Field
26 name="firstName"
27 defaultValue={''}
28 children={(field) => {
29 return (
30 <input
31 data-testid="fieldinput"
32 value={field.state.value}
33 onBlur={field.handleBlur}
34 onChange={(e) => field.handleChange(e.target.value)}
35 />
36 )
37 }}
38 />
39 </>
40 )
41 }
42​
43 const { getByTestId, queryByText } = render(<Comp />)
44 const input = getByTestId('fieldinput')
45 expect(queryByText('FirstName')).not.toBeInTheDocument()
46 await user.type(input, 'FirstName')
47 expect(input).toHaveValue('FirstName')
48 })
49​
50 it('should allow default values to be set', async () => {
51 type Person = {
52 firstName: string
53 lastName: string
54 }
55​
56 function Comp() {
57 const form = useForm({
58 defaultValues: {
59 firstName: 'FirstName',
60 lastName: 'LastName',
61 } as Person,
62 })
63​
64 return (
65 <>
66 <form.Field
67 name="firstName"
68 children={(field) => {
69 return <p>{field.state.value}</p>
70 }}
71 />
72 </>
73 )
74 }
75​
76 const { findByText, queryByText } = render(<Comp />)
77 expect(await findByText('FirstName')).toBeInTheDocument()
78 expect(queryByText('LastName')).not.toBeInTheDocument()
79 })
80​
81 it('should handle submitting properly', async () => {
82 function Comp() {
83 const [submittedData, setSubmittedData] = useState<{
84 firstName: string
85 } | null>(null)
86​
87 const form = useForm({
88 defaultValues: {
89 firstName: 'FirstName',
90 },
91 onSubmit: ({ value }) => {
92 setSubmittedData(value)
93 },
94 })
95​
96 return (
97 <>
98 <form.Field
99 name="firstName"
100 children={(field) => {
101 return (
102 <input
103 value={field.state.value}
104 onBlur={field.handleBlur}
105 onChange={(e) => field.handleChange(e.target.value)}
106 placeholder={'First name'}
107 />
108 )
109 }}
110 />
111 <button onClick={form.handleSubmit}>Submit</button>
112 {submittedData && <p>Submitted data: {submittedData.firstName}</p>}
113 </>
114 )
115 }
116​
117 const { findByPlaceholderText, getByText } = render(<Comp />)
118 const input = await findByPlaceholderText('First name')
119 await user.clear(input)
120 await user.type(input, 'OtherName')
121 await user.click(getByText('Submit'))
122 await waitFor(() =>
123 expect(getByText('Submitted data: OtherName')).toBeInTheDocument(),
124 )
125 })
126​
127 it('should run on form mount', async () => {
128 function Comp() {
129 const [formMounted, setFormMounted] = useState(false)
130 const [mountForm, setMountForm] = useState(false)
131​
132 const form = useForm({
133 defaultValues: {
134 firstName: 'FirstName',
135 },
136 validators: {
137 onMount: () => {
138 setFormMounted(true)
139 return undefined
140 },
141 },
142 })
143​
144 return (
145 <>
146 {mountForm ? (
147 <>
148 <h1>{formMounted ? 'Form mounted' : 'Not mounted'}</h1>
149 </>
150 ) : (
151 <button onClick={() => setMountForm(true)}>Mount form</button>
152 )}
153 </>
154 )
155 }
156​
157 const { getByText } = render(<Comp />)
158 await user.click(getByText('Mount form'))
159 await waitFor(() => expect(getByText('Form mounted')).toBeInTheDocument())
160 })
161​
162 it('should validate async on change for the form', async () => {
163 type Person = {
164 firstName: string
165 lastName: string
166 }
167 const error = 'Please enter a different value'
168​
169 function Comp() {
170 const form = useForm({
171 defaultValues: {
172 firstName: '',
173 lastName: '',
174 } as Person,
175 validators: {
176 onChange() {
177 return error
178 },
179 },
180 })
181 const onChangeError = useStore(form.store, (s) => s.errorMap.onChange)
182 return (
183 <>
184 <form.Field
185 name="firstName"
186 children={(field) => (
187 <input
188 data-testid="fieldinput"
189 name={field.name}
190 value={field.state.value}
191 onBlur={field.handleBlur}
192 onChange={(e) => field.handleChange(e.target.value)}
193 />
194 )}
195 />
196 <p>{onChangeError?.toString()}</p>
197 </>
198 )
199 }
200​
201 const { getByTestId, getByText, queryByText } = render(<Comp />)
202 const input = getByTestId('fieldinput')
203 expect(queryByText(error)).not.toBeInTheDocument()
204 await user.type(input, 'other')
205 await waitFor(() => getByText(error))
206 expect(getByText(error)).toBeInTheDocument()
207 })
208​
209 it('should not validate on change if isTouched is false', async () => {
210 type Person = {
211 firstName: string
212 lastName: string
213 }
214 const error = 'Please enter a different value'
215​
216 function Comp() {
217 const form = useForm({
218 defaultValues: {
219 firstName: '',
220 lastName: '',
221 } as Person,
222 validators: {
223 onChange: ({ value }) =>
224 value.firstName === 'other' ? error : undefined,
225 },
226 })
227​
228 const errors = useStore(form.store, (s) => s.errors)
229 return (
230 <>
231 <form.Field
232 name="firstName"
233 children={(field) => (
234 <div>
235 <input
236 data-testid="fieldinput"
237 name={field.name}
238 value={field.state.value}
239 onBlur={field.handleBlur}
240 onChange={(e) =>
241 field.setValue(e.target.value, {
242 dontUpdateMeta: true,
243 })
244 }
245 />
246 <p>{errors}</p>
247 </div>
248 )}
249 />
250 </>
251 )
252 }
253​
254 const { getByTestId, queryByText } = render(<Comp />)
255 const input = getByTestId('fieldinput')
256 await user.type(input, 'other')
257 expect(queryByText(error)).not.toBeInTheDocument()
258 })
259​
260 it('should validate on change if isTouched is true', async () => {
261 type Person = {
262 firstName: string
263 lastName: string
264 }
265 const error = 'Please enter a different value'
266​
267 function Comp() {
268 const form = useForm({
269 defaultValues: {
270 firstName: '',
271 lastName: '',
272 } as Person,
273 validators: {
274 onChange: ({ value }) =>
275 value.firstName === 'other' ? error : undefined,
276 },
277 })
278 const errors = useStore(form.store, (s) => s.errorMap)
279 return (
280 <>
281 <form.Field
282 name="firstName"
283 defaultMeta={{ isTouched: true }}
284 children={(field) => (
285 <div>
286 <input
287 data-testid="fieldinput"
288 name={field.name}
289 value={field.state.value}
290 onBlur={field.handleBlur}
291 onChange={(e) => field.handleChange(e.target.value)}
292 />
293 <p>{errors.onChange?.toString()}</p>
294 </div>
295 )}
296 />
297 </>
298 )
299 }
300​
301 const { getByTestId, getByText, queryByText } = render(<Comp />)
302 const input = getByTestId('fieldinput')
303 expect(queryByText(error)).not.toBeInTheDocument()
304 await user.type(input, 'other')
305 expect(getByText(error)).toBeInTheDocument()
306 })
307​
308 it('should validate on change and on blur', async () => {
309 const onChangeError = 'Please enter a different value (onChangeError)'
310 const onBlurError = 'Please enter a different value (onBlurError)'
311​
312 function Comp() {
313 const form = useForm({
314 defaultValues: {
315 firstName: '',
316 },
317 validators: {
318 onChange: ({ value }) => {
319 if (value.firstName === 'other') return onChangeError
320 return undefined
321 },
322 onBlur: ({ value }) => {
323 if (value.firstName === 'other') return onBlurError
324 return undefined
325 },
326 },
327 })
328​
329 const errors = useStore(form.store, (s) => s.errorMap)
330 return (
331 <>
332 <form.Field
333 name="firstName"
334 defaultMeta={{ isTouched: true }}
335 children={(field) => (
336 <div>
337 <input
338 data-testid="fieldinput"
339 name={field.name}
340 value={field.state.value}
341 onBlur={field.handleBlur}
342 onChange={(e) => field.handleChange(e.target.value)}
343 />
344 <p>{errors.onChange?.toString()}</p>
345 <p>{errors.onBlur?.toString()}</p>
346 </div>
347 )}
348 />
349 </>
350 )
351 }
352 const { getByTestId, getByText, queryByText } = render(<Comp />)
353 const input = getByTestId('fieldinput')
354 expect(queryByText(onChangeError)).not.toBeInTheDocument()
355 expect(queryByText(onBlurError)).not.toBeInTheDocument()
356 await user.type(input, 'other')
357 expect(getByText(onChangeError)).toBeInTheDocument()
358 await user.click(document.body)
359 expect(queryByText(onBlurError)).toBeInTheDocument()
360 })
361​
362 it("should set field errors from the field's validators", async () => {
363 function Comp() {
364 const form = useForm({
365 defaultValues: {
366 firstName: '',
367 },
368 validators: {
369 onChange: ({ value }) => {
370 if (value.firstName === 'other')
371 return {
372 form: 'Something went wrong',
373 fields: {
374 firstName: 'Please enter a different value (onChangeError)',
375 },
376 }
377 return undefined
378 },
379 onBlur: ({ value }) => {
380 if (value.firstName === 'other')
381 return 'Please enter a different value (onBlurError)'
382 return undefined
383 },
384 },
385 })
386​
387 const errors = useStore(form.store, (s) => s.errorMap)
388 return (
389 <>
390 <form.Field
391 name="firstName"
392 defaultMeta={{ isTouched: true }}
393 children={(field) => (
394 <div>
395 <input
396 data-testid="fieldinput"
397 name={field.name}
398 value={field.state.value}
399 onBlur={field.handleBlur}
400 onChange={(e) => field.handleChange(e.target.value)}
401 />
402 <p data-testid={'field-onchange'}>
403 {field.state.meta.errorMap.onChange}
404 </p>
405 </div>
406 )}
407 />
408 <p data-testid={'form-onchange'}>{errors.onChange?.toString()}</p>
409 <p data-testid={'form-onblur'}>{errors.onBlur?.toString()}</p>
410 </>
411 )
412 }
413 const { getByTestId } = render(<Comp />)
414​
415 expect(getByTestId('form-onchange')).toHaveTextContent('')
416​
417 const input = getByTestId('fieldinput')
418​
419 await user.type(input, 'other')
420 expect(getByTestId('form-onchange')).toHaveTextContent(
421 'Something went wrong',
422 )
423 expect(getByTestId('field-onchange')).toHaveTextContent(
424 'Please enter a different value (onChangeError)',
425 )
426​
427 await user.click(document.body)
428 expect(getByTestId('form-onblur')).toHaveTextContent(
429 'Please enter a different value (onBlurError)',
430 )
431 })
432​
433 it('should validate async on change', async () => {
434 type Person = {
435 firstName: string
436 lastName: string
437 }
438 const error = 'Please enter a different value'
439​
440 function Comp() {
441 const form = useForm({
442 defaultValues: {
443 firstName: '',
444 lastName: '',
445 } as Person,
446 validators: {
447 onChangeAsync: async () => {
448 await sleep(10)
449 return error
450 },
451 },
452 })
453 const errors = useStore(form.store, (s) => s.errorMap)
454 return (
455 <>
456 <form.Field
457 name="firstName"
458 defaultMeta={{ isTouched: true }}
459 children={(field) => (
460 <div>
461 <input
462 data-testid="fieldinput"
463 name={field.name}
464 value={field.state.value}
465 onBlur={field.handleBlur}
466 onChange={(e) => field.handleChange(e.target.value)}
467 />
468 <p>{errors.onChange?.toString()}</p>
469 </div>
470 )}
471 />
472 </>
473 )
474 }
475​
476 const { getByTestId, getByText, queryByText } = render(<Comp />)
477 const input = getByTestId('fieldinput')
478 expect(queryByText(error)).not.toBeInTheDocument()
479 await user.type(input, 'other')
480 await waitFor(() => getByText(error))
481 expect(getByText(error)).toBeInTheDocument()
482 })
483​
484 it("should set field errors from the the form's onChangeAsync validator", async () => {
485 function Comp() {
486 const form = useForm({
487 defaultValues: {
488 firstName: '',
489 lastName: '',
490 },
491 validators: {
492 onChangeAsync: async ({ value }) => {
493 await sleep(10)
494 if (value.firstName === 'other') {
495 return {
496 form: 'Invalid form values',
497 fields: {
498 firstName: 'First name cannot be "other"',
499 },
500 }
501 }
502 return null
503 },
504 },
505 })
506​
507 const errors = useStore(form.store, (s) => s.errorMap)
508​
509 return (
510 <>
511 <form.Field
512 name="firstName"
513 defaultMeta={{ isTouched: true }}
514 children={(field) => (
515 <div>
516 <input
517 data-testid="fieldinput"
518 name={field.name}
519 value={field.state.value}
520 onBlur={field.handleBlur}
521 onChange={(e) => field.handleChange(e.target.value)}
522 />
523 <p data-testid="field-error">
524 {field.state.meta.errorMap.onChange}
525 </p>
526 </div>
527 )}
528 />
529 <p data-testid="form-error">{errors.onChange?.toString()}</p>
530 </>
531 )
532 }
533​
534 const { getByTestId } = render(<Comp />)
535 const input = getByTestId('fieldinput')
536 const firstNameErrorElement = getByTestId('field-error')
537 const formErrorElement = getByTestId('form-error')
538​
539 expect(firstNameErrorElement).toBeEmptyDOMElement()
540 expect(formErrorElement).toBeEmptyDOMElement()
541​
542 await user.type(input, 'other')
543​
544 await waitFor(() => {
545 expect(firstNameErrorElement).not.toBeEmptyDOMElement()
546 })
547 expect(firstNameErrorElement).toHaveTextContent(
548 'First name cannot be "other"',
549 )
550 expect(formErrorElement).toHaveTextContent('Invalid form values')
551 })
552​
553 it('should validate async on change and async on blur', async () => {
554 type Person = {
555 firstName: string
556 lastName: string
557 }
558 const onChangeError = 'Please enter a different value (onChangeError)'
559 const onBlurError = 'Please enter a different value (onBlurError)'
560​
561 function Comp() {
562 const form = useForm({
563 defaultValues: {
564 firstName: '',
565 lastName: '',
566 } as Person,
567 validators: {
568 onChangeAsync: async () => {
569 await sleep(10)
570 return onChangeError
571 },
572 onBlurAsync: async () => {
573 await sleep(10)
574 return onBlurError
575 },
576 },
577 })
578 const errors = useStore(form.store, (s) => s.errorMap)
579​
580 return (
581 <>
582 <form.Field
583 name="firstName"
584 defaultMeta={{ isTouched: true }}
585 children={(field) => (
586 <div>
587 <input
588 data-testid="fieldinput"
589 name={field.name}
590 value={field.state.value}
591 onBlur={field.handleBlur}
592 onChange={(e) => field.handleChange(e.target.value)}
593 />
594 <p>{errors.onChange?.toString()}</p>
595 <p>{errors.onBlur?.toString()}</p>
596 </div>
597 )}
598 />
599 </>
600 )
601 }
602​
603 const { getByTestId, getByText, queryByText } = render(<Comp />)
604 const input = getByTestId('fieldinput')
605​
606 expect(queryByText(onChangeError)).not.toBeInTheDocument()
607 expect(queryByText(onBlurError)).not.toBeInTheDocument()
608 await user.type(input, 'other')
609 await waitFor(() => getByText(onChangeError))
610 expect(getByText(onChangeError)).toBeInTheDocument()
611 await user.click(document.body)
612 await waitFor(() => getByText(onBlurError))
613 expect(getByText(onBlurError)).toBeInTheDocument()
614 })
615​
616 it('should validate async on change with debounce', async () => {
617 type Person = {
618 firstName: string
619 lastName: string
620 }
621 const mockFn = vi.fn()
622 const error = 'Please enter a different value'
623​
624 function Comp() {
625 const form = useForm({
626 defaultValues: {
627 firstName: '',
628 lastName: '',
629 } as Person,
630 validators: {
631 onChangeAsyncDebounceMs: 100,
632 onChangeAsync: async () => {
633 mockFn()
634 await sleep(10)
635 return error
636 },
637 },
638 })
639 const errors = useStore(form.store, (s) => s.errors)
640​
641 return (
642 <>
643 <form.Field
644 name="firstName"
645 defaultMeta={{ isTouched: true }}
646 children={(field) => (
647 <div>
648 <input
649 data-testid="fieldinput"
650 name={field.name}
651 value={field.state.value}
652 onBlur={field.handleBlur}
653 onChange={(e) => field.handleChange(e.target.value)}
654 />
655 <p>{errors}</p>
656 </div>
657 )}
658 />
659 </>
660 )
661 }
662​
663 const { getByTestId, getByText } = render(<Comp />)
664 const input = getByTestId('fieldinput')
665 await user.type(input, 'other')
666 // mockFn will have been called 5 times without onChangeAsyncDebounceMs
667 expect(mockFn).toHaveBeenCalledTimes(0)
668 await waitFor(() => getByText(error))
669 expect(getByText(error)).toBeInTheDocument()
670 })
671​
672 it("should set errors on the fields from the form's onChange validator", async () => {
673 function Comp() {
674 const form = useForm({
675 defaultValues: {
676 firstName: '',
677 lastName: '',
678 },
679 validators: {
680 onChange: ({ value }) => {
681 if (value.firstName === 'Tom') {
682 return {
683 form: 'Something went wrong',
684 fields: { firstName: 'Please enter a different value' },
685 }
686 }
687 return null
688 },
689 },
690 })
691​
692 const onChangeError = useStore(form.store, (s) => s.errorMap.onChange)
693​
694 return (
695 <>
696 <form.Field
697 name="firstName"
698 children={(field) => (
699 <>
700 <input
701 data-testid="fieldinput"
702 name={field.name}
703 value={field.state.value}
704 onBlur={field.handleBlur}
705 onChange={(e) => field.handleChange(e.target.value)}
706 />
707​
708 <p data-testid="field-error">
709 {field.state.meta.errors.join('')}
710 </p>
711 </>
712 )}
713 />
714 <p data-testid="form-error">{onChangeError?.toString()}</p>
715 </>
716 )
717 }
718​
719 const { getByTestId, queryByText } = render(<Comp />)
720 const input = getByTestId('fieldinput')
721 const fieldError = getByTestId('field-error')
722 const formError = getByTestId('form-error')
723​
724 expect(
725 queryByText('Please enter a different value'),
726 ).not.toBeInTheDocument()
727 expect(queryByText('Something went wrong')).not.toBeInTheDocument()
728​
729 await user.type(input, 'Tom')
730 await waitFor(() =>
731 expect(fieldError.textContent).toBe('Please enter a different value'),
732 )
733 await waitFor(() =>
734 expect(formError.textContent).toBe('Something went wrong'),
735 )
736 })
737​
738 it('should not cause infinite re-renders when listening to state.errors', () => {
739 const fn = vi.fn()
740​
741 function Comp() {
742 const form = useForm({
743 defaultValues: {
744 firstName: '',
745 lastName: '',
746 },
747 onSubmit: async ({ value }) => {
748 // Do something with form data
749 console.log(value)
750 },
751 })
752​
753 const { errors } = useStore(form.store, (state) => ({
754 errors: state.errors,
755 }))
756​
757 useEffect(() => {
758 fn(errors)
759 }, [errors])
760​
761 return null
762 }
763​
764 render(<Comp />)
765​
766 expect(fn).toHaveBeenCalledTimes(1)
767 })
768​
769 it('should not cause infinite re-renders when listening to state', () => {
770 const fn = vi.fn()
771​
772 function Comp() {
773 const form = useForm({
774 defaultValues: {
775 firstName: '',
776 lastName: '',
777 },
778 onSubmit: async ({ value }) => {
779 // Do something with form data
780 console.log(value)
781 },
782 })
783​
784 const { values } = useStore(form.store)
785​
786 useEffect(() => {
787 fn(values)
788 }, [values])
789​
790 return null
791 }
792​
793 render(<Comp />)
794​
795 expect(fn).toHaveBeenCalledTimes(1)
796 })
797})