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

createForm.test.tsx

644 lines18.3 KB

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