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 { 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(form.store.subscribe(() => setErrors(form.state.errorMap)))
218β
219 return (
220 <>
221 <form.Field
222 name="firstName"
223 defaultMeta={{ isTouched: true }}
224 children={(field) => {
225 return (
226 <div>
227 <input
228 data-testid="fieldinput"
229 name={field().name}
230 value={field().state.value}
231 onBlur={field().handleBlur}
232 onInput={(e) =>
233 field().setValue(e.currentTarget.value, {
234 dontUpdateMeta: true,
235 })
236 }
237 />
238 <p>{errors()?.onChange?.toString()}</p>
239 </div>
240 )
241 }}
242 />
243 </>
244 )
245 }
246β
247 const { getByTestId, getByText, queryByText } = render(() => <Comp />)
248 const input = getByTestId('fieldinput')
249 expect(queryByText(error)).not.toBeInTheDocument()
250 await user.type(input, 'other')
251 expect(getByText(error)).toBeInTheDocument()
252 })
253β
254 it('should validate on change and on blur', async () => {
255 type Person = {
256 firstName: string
257 lastName: string
258 }
259 const onChangeError = 'Please enter a different value (onChangeError)'
260 const onBlurError = 'Please enter a different value (onBlurError)'
261β
262 function Comp() {
263 const form = createForm(() => ({
264 defaultValues: {} as Person,
265 validators: {
266 onChange: ({ value }) =>
267 value.firstName.includes('other') ? onChangeError : undefined,
268 onBlur: ({ value }) =>
269 value.firstName.includes('other') ? onBlurError : undefined,
270 },
271 }))
272β
273 const [errors, setErrors] = createSignal<FormValidationErrorMap>()
274 onCleanup(form.store.subscribe(() => setErrors(form.state.errorMap)))
275β
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 onInput={(e) => field().handleChange(e.currentTarget.value)}
289 />
290 <p>{errors()?.onChange?.toString()}</p>
291 <p>{errors()?.onBlur?.toString()}</p>
292 </div>
293 )}
294 />
295 </>
296 )
297 }
298β
299 const { getByTestId, getByText, queryByText } = render(() => <Comp />)
300 const input = getByTestId('fieldinput')
301 expect(queryByText(onChangeError)).not.toBeInTheDocument()
302 expect(queryByText(onBlurError)).not.toBeInTheDocument()
303 await user.type(input, 'other')
304 expect(getByText(onChangeError)).toBeInTheDocument()
305 await user.click(document.body)
306 expect(queryByText(onBlurError)).toBeInTheDocument()
307 })
308β
309 it('should validate async on change', async () => {
310 type Person = {
311 firstName: string
312 lastName: string
313 }
314 const error = 'Please enter a different value'
315β
316 function Comp() {
317 const form = createForm(() => ({
318 defaultValues: {} as Person,
319 validators: {
320 onChangeAsync: async () => {
321 await sleep(10)
322 return error
323 },
324 },
325 }))
326β
327 const [errors, setErrors] = createSignal<FormValidationErrorMap>()
328 onCleanup(form.store.subscribe(() => setErrors(form.state.errorMap)))
329β
330 return (
331 <>
332 <form.Field
333 name="firstName"
334 defaultMeta={{ isTouched: true }}
335 children={(field) => (
336 <div>
337 <input
338 data-testid="fieldinput"
339 name={field().name}
340 value={field().state.value}
341 onBlur={field().handleBlur}
342 onInput={(e) => field().handleChange(e.currentTarget.value)}
343 />
344 <p>{errors()?.onChange?.toString()}</p>
345 </div>
346 )}
347 />
348 </>
349 )
350 }
351β
352 const { getByTestId, getByText, queryByText } = render(() => <Comp />)
353 const input = getByTestId('fieldinput')
354 expect(queryByText(error)).not.toBeInTheDocument()
355 await user.type(input, 'other')
356 await waitFor(() => getByText(error))
357 expect(getByText(error)).toBeInTheDocument()
358 })
359β
360 it('should validate async on change and async on blur', async () => {
361 type Person = {
362 firstName: string
363 lastName: string
364 }
365 const onChangeError = 'Please enter a different value (onChangeError)'
366 const onBlurError = 'Please enter a different value (onBlurError)'
367β
368 function Comp() {
369 const form = createForm(() => ({
370 defaultValues: {} as Person,
371 validators: {
372 async onChangeAsync() {
373 await sleep(10)
374 return onChangeError
375 },
376 async onBlurAsync() {
377 await sleep(10)
378 return onBlurError
379 },
380 },
381 }))
382β
383 const [errors, setErrors] = createSignal<FormValidationErrorMap>()
384 onCleanup(form.store.subscribe(() => setErrors(form.state.errorMap)))
385β
386 return (
387 <>
388 <form.Field
389 name="firstName"
390 defaultMeta={{ isTouched: true }}
391 children={(field) => (
392 <div>
393 <input
394 data-testid="fieldinput"
395 name={field().name}
396 value={field().state.value}
397 onBlur={field().handleBlur}
398 onInput={(e) => field().handleChange(e.currentTarget.value)}
399 />
400 <p>{errors()?.onChange?.toString()}</p>
401 <p>{errors()?.onBlur?.toString()}</p>
402 </div>
403 )}
404 />
405 </>
406 )
407 }
408β
409 const { getByTestId, getByText, queryByText } = render(() => <Comp />)
410 const input = getByTestId('fieldinput')
411β
412 expect(queryByText(onChangeError)).not.toBeInTheDocument()
413 expect(queryByText(onBlurError)).not.toBeInTheDocument()
414 await user.type(input, 'other')
415 await waitFor(() => getByText(onChangeError))
416 expect(getByText(onChangeError)).toBeInTheDocument()
417 await user.click(document.body)
418 await waitFor(() => getByText(onBlurError))
419 expect(getByText(onBlurError)).toBeInTheDocument()
420 })
421β
422 it('should validate async on change with debounce', async () => {
423 type Person = {
424 firstName: string
425 lastName: string
426 }
427 const mockFn = vi.fn()
428 const error = 'Please enter a different value'
429β
430 function Comp() {
431 const form = createForm(() => ({
432 defaultValues: {} as Person,
433 validators: {
434 onChangeAsyncDebounceMs: 100,
435 onChangeAsync: async () => {
436 mockFn()
437 await sleep(10)
438 return error
439 },
440 },
441 }))
442β
443 const [errors, setErrors] = createSignal<string>()
444 onCleanup(
445 form.store.subscribe(() =>
446 setErrors(form.state.errorMap.onChange?.toString() || ''),
447 ),
448 )
449β
450 return (
451 <>
452 <form.Field
453 name="firstName"
454 defaultMeta={{ isTouched: true }}
455 children={(field) => (
456 <div>
457 <input
458 data-testid="fieldinput"
459 name={field().name}
460 value={field().state.value}
461 onBlur={field().handleBlur}
462 onInput={(e) => field().handleChange(e.currentTarget.value)}
463 />
464 <p>{errors()}</p>
465 </div>
466 )}
467 />
468 </>
469 )
470 }
471β
472 const { getByTestId, getByText } = render(() => <Comp />)
473 const input = getByTestId('fieldinput')
474 await user.type(input, 'other')
475 // mockFn will have been called 5 times without onChangeAsyncDebounceMs
476 expect(mockFn).toHaveBeenCalledTimes(0)
477 await waitFor(() => getByText(error))
478 expect(getByText(error)).toBeInTheDocument()
479 })
480})