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

useForm.test.tsx

734 lines20.5 KB

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