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 { 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}</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}</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}</p>
342 <p>{errors.onBlur}</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 validate async on change', async () => {
360 type Person = {
361 firstName: string
362 lastName: string
363 }
364 const error = 'Please enter a different value'
365β
366 function Comp() {
367 const form = useForm({
368 defaultValues: {
369 firstName: '',
370 lastName: '',
371 } as Person,
372 validators: {
373 onChangeAsync: async () => {
374 await sleep(10)
375 return error
376 },
377 },
378 })
379 const errors = form.useStore((s) => s.errorMap)
380 return (
381 <>
382 <form.Field
383 name="firstName"
384 defaultMeta={{ isTouched: true }}
385 children={(field) => (
386 <div>
387 <input
388 data-testid="fieldinput"
389 name={field.name}
390 value={field.state.value}
391 onBlur={field.handleBlur}
392 onChange={(e) => field.handleChange(e.target.value)}
393 />
394 <p>{errors.onChange}</p>
395 </div>
396 )}
397 />
398 </>
399 )
400 }
401β
402 const { getByTestId, getByText, queryByText } = render(<Comp />)
403 const input = getByTestId('fieldinput')
404 expect(queryByText(error)).not.toBeInTheDocument()
405 await user.type(input, 'other')
406 await waitFor(() => getByText(error))
407 expect(getByText(error)).toBeInTheDocument()
408 })
409β
410 it('should validate async on change and async on blur', async () => {
411 type Person = {
412 firstName: string
413 lastName: string
414 }
415 const onChangeError = 'Please enter a different value (onChangeError)'
416 const onBlurError = 'Please enter a different value (onBlurError)'
417β
418 function Comp() {
419 const form = useForm({
420 defaultValues: {
421 firstName: '',
422 lastName: '',
423 } as Person,
424 validators: {
425 onChangeAsync: async () => {
426 await sleep(10)
427 return onChangeError
428 },
429 onBlurAsync: async () => {
430 await sleep(10)
431 return onBlurError
432 },
433 },
434 })
435 const errors = form.useStore((s) => s.errorMap)
436β
437 return (
438 <>
439 <form.Field
440 name="firstName"
441 defaultMeta={{ isTouched: true }}
442 children={(field) => (
443 <div>
444 <input
445 data-testid="fieldinput"
446 name={field.name}
447 value={field.state.value}
448 onBlur={field.handleBlur}
449 onChange={(e) => field.handleChange(e.target.value)}
450 />
451 <p>{errors.onChange}</p>
452 <p>{errors.onBlur}</p>
453 </div>
454 )}
455 />
456 </>
457 )
458 }
459β
460 const { getByTestId, getByText, queryByText } = render(<Comp />)
461 const input = getByTestId('fieldinput')
462β
463 expect(queryByText(onChangeError)).not.toBeInTheDocument()
464 expect(queryByText(onBlurError)).not.toBeInTheDocument()
465 await user.type(input, 'other')
466 await waitFor(() => getByText(onChangeError))
467 expect(getByText(onChangeError)).toBeInTheDocument()
468 await user.click(document.body)
469 await waitFor(() => getByText(onBlurError))
470 expect(getByText(onBlurError)).toBeInTheDocument()
471 })
472β
473 it('should validate async on change with debounce', async () => {
474 type Person = {
475 firstName: string
476 lastName: string
477 }
478 const mockFn = vi.fn()
479 const error = 'Please enter a different value'
480β
481 function Comp() {
482 const form = useForm({
483 defaultValues: {
484 firstName: '',
485 lastName: '',
486 } as Person,
487 validators: {
488 onChangeAsyncDebounceMs: 100,
489 onChangeAsync: async () => {
490 mockFn()
491 await sleep(10)
492 return error
493 },
494 },
495 })
496 const errors = form.useStore((s) => s.errors)
497β
498 return (
499 <>
500 <form.Field
501 name="firstName"
502 defaultMeta={{ isTouched: true }}
503 children={(field) => (
504 <div>
505 <input
506 data-testid="fieldinput"
507 name={field.name}
508 value={field.state.value}
509 onBlur={field.handleBlur}
510 onChange={(e) => field.handleChange(e.target.value)}
511 />
512 <p>{errors}</p>
513 </div>
514 )}
515 />
516 </>
517 )
518 }
519β
520 const { getByTestId, getByText } = render(<Comp />)
521 const input = getByTestId('fieldinput')
522 await user.type(input, 'other')
523 // mockFn will have been called 5 times without onChangeAsyncDebounceMs
524 expect(mockFn).toHaveBeenCalledTimes(0)
525 await waitFor(() => getByText(error))
526 expect(getByText(error)).toBeInTheDocument()
527 })
528})