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

createField.test.tsx

628 lines19.4 KB

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