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