Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import { render, screen, waitFor } from '@solidjs/testing-library'
3import { userEvent } from '@testing-library/user-event'
4import { Show, createSignal, onCleanup } from 'solid-js'
5import { createForm } from '../src/index'
6import { sleep } from './utils'
7import type { ValidationErrorMap } from '@tanstack/form-core'
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<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<Person>(() => ({
160 validators: {
161 onChange: ({ value }) =>
162 value.firstName.includes('other') ? error : undefined,
163 },
164 }))
165β
166 const errors = form.useStore((s) => s.errors)
167β
168 return (
169 <>
170 <form.Field
171 name="firstName"
172 children={(field) => (
173 <div>
174 <input
175 data-testid="fieldinput"
176 name={field().name}
177 value={field().state.value}
178 onBlur={field().handleBlur}
179 onInput={(e) =>
180 field().setValue(e.currentTarget.value, {
181 dontUpdateMeta: true,
182 })
183 }
184 />
185 <p>{errors().join(',')}</p>
186 </div>
187 )}
188 />
189 </>
190 )
191 }
192β
193 const { getByTestId, queryByText } = render(() => <Comp />)
194 const input = getByTestId('fieldinput')
195 await user.type(input, 'other')
196 expect(queryByText(error)).not.toBeInTheDocument()
197 })
198β
199 it('should validate on change if isTouched is true', async () => {
200 type Person = {
201 firstName: string
202 lastName: string
203 }
204 const error = 'Please enter a different value'
205β
206 function Comp() {
207 const form = createForm<Person>(() => ({
208 validators: {
209 onChange: ({ value }) =>
210 value.firstName.includes('other') ? error : undefined,
211 },
212 }))
213β
214 const [errors, setErrors] = createSignal<ValidationErrorMap>()
215 onCleanup(form.store.subscribe(() => setErrors(form.state.errorMap)))
216β
217 return (
218 <>
219 <form.Field
220 name="firstName"
221 defaultMeta={{ isTouched: true }}
222 children={(field) => {
223 return (
224 <div>
225 <input
226 data-testid="fieldinput"
227 name={field().name}
228 value={field().state.value}
229 onBlur={field().handleBlur}
230 onInput={(e) =>
231 field().setValue(e.currentTarget.value, {
232 dontUpdateMeta: true,
233 })
234 }
235 />
236 <p>{errors()?.onChange}</p>
237 </div>
238 )
239 }}
240 />
241 </>
242 )
243 }
244β
245 const { getByTestId, getByText, queryByText } = render(() => <Comp />)
246 const input = getByTestId('fieldinput')
247 expect(queryByText(error)).not.toBeInTheDocument()
248 await user.type(input, 'other')
249 expect(getByText(error)).toBeInTheDocument()
250 })
251β
252 it('should validate on change and on blur', async () => {
253 type Person = {
254 firstName: string
255 lastName: string
256 }
257 const onChangeError = 'Please enter a different value (onChangeError)'
258 const onBlurError = 'Please enter a different value (onBlurError)'
259β
260 function Comp() {
261 const form = createForm<Person>(() => ({
262 validators: {
263 onChange: ({ value }) =>
264 value.firstName.includes('other') ? onChangeError : undefined,
265 onBlur: ({ value }) =>
266 value.firstName.includes('other') ? onBlurError : undefined,
267 },
268 }))
269β
270 const [errors, setErrors] = createSignal<ValidationErrorMap>()
271 onCleanup(form.store.subscribe(() => setErrors(form.state.errorMap)))
272β
273 return (
274 <>
275 <form.Field
276 name="firstName"
277 defaultMeta={{ isTouched: true }}
278 children={(field) => (
279 <div>
280 <input
281 data-testid="fieldinput"
282 name={field().name}
283 value={field().state.value}
284 onBlur={field().handleBlur}
285 onInput={(e) => field().handleChange(e.currentTarget.value)}
286 />
287 <p>{errors()?.onChange}</p>
288 <p>{errors()?.onBlur}</p>
289 </div>
290 )}
291 />
292 </>
293 )
294 }
295β
296 const { getByTestId, getByText, queryByText } = render(() => <Comp />)
297 const input = getByTestId('fieldinput')
298 expect(queryByText(onChangeError)).not.toBeInTheDocument()
299 expect(queryByText(onBlurError)).not.toBeInTheDocument()
300 await user.type(input, 'other')
301 expect(getByText(onChangeError)).toBeInTheDocument()
302 await user.click(document.body)
303 expect(queryByText(onBlurError)).toBeInTheDocument()
304 })
305β
306 it('should validate async on change', async () => {
307 type Person = {
308 firstName: string
309 lastName: string
310 }
311 const error = 'Please enter a different value'
312β
313 function Comp() {
314 const form = createForm<Person>(() => ({
315 validators: {
316 onChangeAsync: async () => {
317 await sleep(10)
318 return error
319 },
320 },
321 }))
322β
323 const [errors, setErrors] = createSignal<ValidationErrorMap>()
324 onCleanup(form.store.subscribe(() => setErrors(form.state.errorMap)))
325β
326 return (
327 <>
328 <form.Field
329 name="firstName"
330 defaultMeta={{ isTouched: true }}
331 children={(field) => (
332 <div>
333 <input
334 data-testid="fieldinput"
335 name={field().name}
336 value={field().state.value}
337 onBlur={field().handleBlur}
338 onInput={(e) => field().handleChange(e.currentTarget.value)}
339 />
340 <p>{errors()?.onChange}</p>
341 </div>
342 )}
343 />
344 </>
345 )
346 }
347β
348 const { getByTestId, getByText, queryByText } = render(() => <Comp />)
349 const input = getByTestId('fieldinput')
350 expect(queryByText(error)).not.toBeInTheDocument()
351 await user.type(input, 'other')
352 await waitFor(() => getByText(error))
353 expect(getByText(error)).toBeInTheDocument()
354 })
355β
356 it('should validate async on change and async on blur', async () => {
357 type Person = {
358 firstName: string
359 lastName: string
360 }
361 const onChangeError = 'Please enter a different value (onChangeError)'
362 const onBlurError = 'Please enter a different value (onBlurError)'
363β
364 function Comp() {
365 const form = createForm<Person>(() => ({
366 validators: {
367 async onChangeAsync() {
368 await sleep(10)
369 return onChangeError
370 },
371 async onBlurAsync() {
372 await sleep(10)
373 return onBlurError
374 },
375 },
376 }))
377β
378 const [errors, setErrors] = createSignal<ValidationErrorMap>()
379 onCleanup(form.store.subscribe(() => setErrors(form.state.errorMap)))
380β
381 return (
382 <>
383 <form.Field
384 name="firstName"
385 defaultMeta={{ isTouched: true }}
386 children={(field) => (
387 <div>
388 <input
389 data-testid="fieldinput"
390 name={field().name}
391 value={field().state.value}
392 onBlur={field().handleBlur}
393 onInput={(e) => field().handleChange(e.currentTarget.value)}
394 />
395 <p>{errors()?.onChange}</p>
396 <p>{errors()?.onBlur}</p>
397 </div>
398 )}
399 />
400 </>
401 )
402 }
403β
404 const { getByTestId, getByText, queryByText } = render(() => <Comp />)
405 const input = getByTestId('fieldinput')
406β
407 expect(queryByText(onChangeError)).not.toBeInTheDocument()
408 expect(queryByText(onBlurError)).not.toBeInTheDocument()
409 await user.type(input, 'other')
410 await waitFor(() => getByText(onChangeError))
411 expect(getByText(onChangeError)).toBeInTheDocument()
412 await user.click(document.body)
413 await waitFor(() => getByText(onBlurError))
414 expect(getByText(onBlurError)).toBeInTheDocument()
415 })
416β
417 it('should validate async on change with debounce', async () => {
418 type Person = {
419 firstName: string
420 lastName: string
421 }
422 const mockFn = vi.fn()
423 const error = 'Please enter a different value'
424β
425 function Comp() {
426 const form = createForm<Person>(() => ({
427 validators: {
428 onChangeAsyncDebounceMs: 100,
429 onChangeAsync: async () => {
430 mockFn()
431 await sleep(10)
432 return error
433 },
434 },
435 }))
436β
437 const [errors, setErrors] = createSignal<string>()
438 onCleanup(
439 form.store.subscribe(() =>
440 setErrors(form.state.errorMap.onChange || ''),
441 ),
442 )
443β
444 return (
445 <>
446 <form.Field
447 name="firstName"
448 defaultMeta={{ isTouched: true }}
449 children={(field) => (
450 <div>
451 <input
452 data-testid="fieldinput"
453 name={field().name}
454 value={field().state.value}
455 onBlur={field().handleBlur}
456 onInput={(e) => field().handleChange(e.currentTarget.value)}
457 />
458 <p>{errors()}</p>
459 </div>
460 )}
461 />
462 </>
463 )
464 }
465β
466 const { getByTestId, getByText } = render(() => <Comp />)
467 const input = getByTestId('fieldinput')
468 await user.type(input, 'other')
469 // mockFn will have been called 5 times without onChangeAsyncDebounceMs
470 expect(mockFn).toHaveBeenCalledTimes(0)
471 await waitFor(() => getByText(error))
472 expect(getByText(error)).toBeInTheDocument()
473 })
474})