Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import { render } from '@testing-library/react'
3import { formOptions } from '@tanstack/form-core'
4import userEvent from '@testing-library/user-event'
5import { createFormHook, createFormHookContexts, useStore } from '../src'
6β
7const user = userEvent.setup()
8β
9const { fieldContext, useFieldContext, formContext, useFormContext } =
10 createFormHookContexts()
11β
12function TextField({ label }: { label: string }) {
13 const field = useFieldContext<string>()
14 return (
15 <label>
16 <div>{label}</div>
17 <input
18 value={field.state.value}
19 onChange={(e) => field.handleChange(e.target.value)}
20 />
21 </label>
22 )
23}
24β
25function SubscribeButton({ label }: { label: string }) {
26 const form = useFormContext()
27 return (
28 <form.Subscribe selector={(state) => state.isSubmitting}>
29 {(isSubmitting) => <button disabled={isSubmitting}>{label}</button>}
30 </form.Subscribe>
31 )
32}
33β
34const { useAppForm, withForm, withFieldGroup } = createFormHook({
35 fieldComponents: {
36 TextField,
37 },
38 formComponents: {
39 SubscribeButton,
40 },
41 fieldContext,
42 formContext,
43})
44β
45describe('createFormHook', () => {
46 it('should allow to set default value', () => {
47 type Person = {
48 firstName: string
49 lastName: string
50 }
51β
52 function Comp() {
53 const form = useAppForm({
54 defaultValues: {
55 firstName: 'FirstName',
56 lastName: 'LastName',
57 } as Person,
58 })
59β
60 return (
61 <>
62 <form.AppField
63 name="firstName"
64 children={(field) => <field.TextField label="Testing" />}
65 />
66 </>
67 )
68 }
69β
70 const { getByLabelText } = render(<Comp />)
71 const input = getByLabelText('Testing')
72 expect(input).toHaveValue('FirstName')
73 })
74β
75 it('should handle withForm types properly', () => {
76 const formOpts = formOptions({
77 defaultValues: {
78 firstName: 'John',
79 lastName: 'Doe',
80 },
81 })
82β
83 const ChildForm = withForm({
84 ...formOpts,
85 // Optional, but adds props to the `render` function outside of `form`
86 props: {
87 title: 'Child Form',
88 },
89 render: ({ form, title }) => {
90 return (
91 <div>
92 <p>{title}</p>
93 <form.AppField
94 name="firstName"
95 children={(field) => <field.TextField label="First Name" />}
96 />
97 <form.AppForm>
98 <form.SubscribeButton label="Submit" />
99 </form.AppForm>
100 </div>
101 )
102 },
103 })
104β
105 const Parent = () => {
106 const form = useAppForm({
107 ...formOpts,
108 })
109β
110 return <ChildForm form={form} title={'Testing'} />
111 }
112β
113 const { getByLabelText, getByText } = render(<Parent />)
114 const input = getByLabelText('First Name')
115 expect(input).toHaveValue('John')
116 expect(getByText('Testing')).toBeInTheDocument()
117 })
118β
119 it('should handle withFieldGroup types properly', () => {
120 const formOpts = formOptions({
121 defaultValues: {
122 person: {
123 firstName: 'John',
124 lastName: 'Doe',
125 },
126 },
127 })
128β
129 const ChildForm = withFieldGroup({
130 defaultValues: formOpts.defaultValues.person,
131 // Optional, but adds props to the `render` function outside of `form`
132 props: {
133 title: 'Child Form',
134 },
135 render: ({ group, title }) => {
136 return (
137 <div>
138 <p>{title}</p>
139 <group.AppField
140 name="firstName"
141 children={(field) => <field.TextField label="First Name" />}
142 />
143 <group.AppForm>
144 <group.SubscribeButton label="Submit" />
145 </group.AppForm>
146 </div>
147 )
148 },
149 })
150β
151 const Parent = () => {
152 const form = useAppForm({
153 ...formOpts,
154 })
155β
156 return <ChildForm form={form} fields="person" title={'Testing'} />
157 }
158β
159 const { getByLabelText, getByText } = render(<Parent />)
160 const input = getByLabelText('First Name')
161 expect(input).toHaveValue('John')
162 expect(getByText('Testing')).toBeInTheDocument()
163 })
164β
165 it('should use the correct field name in Field with withFieldGroup', () => {
166 const formOpts = formOptions({
167 defaultValues: {
168 person: {
169 firstName: 'John',
170 lastName: 'Doe',
171 },
172 people: [
173 {
174 firstName: 'Jane',
175 lastName: 'Doe',
176 },
177 {
178 firstName: 'Robert',
179 lastName: 'Doe',
180 },
181 ],
182 },
183 })
184β
185 const ChildFormAsField = withFieldGroup({
186 defaultValues: formOpts.defaultValues.person,
187 render: ({ group }) => {
188 return (
189 <div>
190 <group.AppField
191 name="firstName"
192 children={(field) => <field.TextField label={field.name} />}
193 />
194 <group.AppForm>
195 <group.SubscribeButton label="Submit" />
196 </group.AppForm>
197 </div>
198 )
199 },
200 })
201 const ChildFormAsArray = withFieldGroup({
202 defaultValues: [formOpts.defaultValues.person],
203 props: {
204 title: '',
205 },
206 render: ({ group, title }) => {
207 return (
208 <div>
209 <p>{title}</p>
210 <group.AppField
211 name="[0].firstName"
212 children={(field) => <field.TextField label={field.name} />}
213 />
214 <group.AppForm>
215 <group.SubscribeButton label="Submit" />
216 </group.AppForm>
217 </div>
218 )
219 },
220 })
221β
222 const Parent = () => {
223 const form = useAppForm({
224 ...formOpts,
225 })
226β
227 return (
228 <>
229 <ChildFormAsField form={form} fields="person" />
230 <ChildFormAsArray form={form} fields="people" title="Testing" />
231 <ChildFormAsField form={form} fields="people[1]" />
232 </>
233 )
234 }
235β
236 const { getByLabelText, getByText } = render(<Parent />)
237 const inputField1 = getByLabelText('person.firstName')
238 const inputArray = getByLabelText('people[0].firstName')
239 const inputField2 = getByLabelText('people[1].firstName')
240 expect(inputField1).toHaveValue('John')
241 expect(inputArray).toHaveValue('Jane')
242 expect(inputField2).toHaveValue('Robert')
243 expect(getByText('Testing')).toBeInTheDocument()
244 })
245β
246 it('should forward Field and Subscribe to the form', () => {
247 const formOpts = formOptions({
248 defaultValues: {
249 person: {
250 firstName: 'John',
251 lastName: 'Doe',
252 },
253 },
254 })
255β
256 const ChildFormAsField = withFieldGroup({
257 defaultValues: formOpts.defaultValues.person,
258 render: ({ group }) => {
259 return (
260 <div>
261 <group.Field
262 name="firstName"
263 children={(field) => (
264 <label>
265 <div>{field.name}</div>
266 <input
267 value={field.state.value}
268 onChange={(e) => field.handleChange(e.target.value)}
269 />
270 </label>
271 )}
272 />
273 <group.Subscribe selector={(state) => state.values.lastName}>
274 {(lastName) => <p>{lastName}</p>}
275 </group.Subscribe>
276 </div>
277 )
278 },
279 })
280β
281 const Parent = () => {
282 const form = useAppForm({
283 ...formOpts,
284 })
285 return <ChildFormAsField form={form} fields="person" />
286 }
287β
288 const { getByLabelText, getByText } = render(<Parent />)
289 const input = getByLabelText('person.firstName')
290 expect(input).toHaveValue('John')
291 expect(getByText('Doe')).toBeInTheDocument()
292 })
293β
294 it('should not lose focus on update with withFieldGroup', async () => {
295 const formOpts = formOptions({
296 defaultValues: {
297 person: {
298 firstName: 'John',
299 lastName: 'Doe',
300 },
301 },
302 })
303β
304 const ChildForm = withFieldGroup({
305 defaultValues: formOpts.defaultValues.person,
306 render: function Render({ group }) {
307 const firstName = useStore(
308 group.store,
309 (state) => state.values.firstName,
310 )
311 return (
312 <div>
313 <p>{firstName}</p>
314 <group.Field
315 name="firstName"
316 children={(field) => (
317 <label>
318 <div>{field.name}</div>
319 <input
320 value={field.state.value}
321 onChange={(e) => field.handleChange(e.target.value)}
322 />
323 </label>
324 )}
325 />
326 <group.Subscribe selector={(state) => state.values.lastName}>
327 {(lastName) => <p>{lastName}</p>}
328 </group.Subscribe>
329 </div>
330 )
331 },
332 })
333β
334 const Parent = () => {
335 const form = useAppForm({
336 ...formOpts,
337 })
338 return <ChildForm form={form} fields="person" />
339 }
340β
341 const { getByLabelText } = render(<Parent />)
342β
343 const input = getByLabelText('person.firstName')
344 input.focus()
345 expect(input).toHaveFocus()
346β
347 await user.clear(input)
348 await user.type(input, 'Something')
349β
350 expect(input).toHaveFocus()
351 })
352β
353 it('should allow nesting withFieldGroup in other withFieldGroups', () => {
354 type Nested = {
355 firstName: string
356 }
357 type Wrapper = {
358 field: Nested
359 }
360 type FormValues = {
361 form: Wrapper
362 unrelated: { something: { lastName: string } }
363 }
364β
365 const defaultValues: FormValues = {
366 form: {
367 field: {
368 firstName: 'Test',
369 },
370 },
371 unrelated: {
372 something: {
373 lastName: '',
374 },
375 },
376 }
377β
378 const LensNested = withFieldGroup({
379 defaultValues: defaultValues.form.field,
380 render: function Render({ group }) {
381 return (
382 <group.Field name="firstName">
383 {(field) => <p>{field.name}</p>}
384 </group.Field>
385 )
386 },
387 })
388 const LensWrapper = withFieldGroup({
389 defaultValues: defaultValues.form,
390 render: function Render({ group }) {
391 return (
392 <div>
393 <LensNested form={group} fields="field" />
394 </div>
395 )
396 },
397 })
398β
399 const Parent = () => {
400 const form = useAppForm({
401 defaultValues,
402 })
403 return <LensWrapper form={form} fields="form" />
404 }
405β
406 const { getByText } = render(<Parent />)
407β
408 expect(getByText('form.field.firstName')).toBeInTheDocument()
409 })
410β
411 it('should allow mapping withFieldGroup to different values', () => {
412 const formOpts = formOptions({
413 defaultValues: {
414 unrelated: 'John',
415 values: '',
416 },
417 })
418β
419 const ChildFormAsField = withFieldGroup({
420 defaultValues: { firstName: '', lastName: '' },
421 render: ({ group }) => {
422 return (
423 <div>
424 <group.AppField
425 name="firstName"
426 children={(field) => <field.TextField label={field.name} />}
427 />
428 </div>
429 )
430 },
431 })
432β
433 const Parent = () => {
434 const form = useAppForm({
435 ...formOpts,
436 })
437β
438 return (
439 <ChildFormAsField
440 form={form}
441 fields={{
442 firstName: 'unrelated',
443 lastName: 'values',
444 }}
445 />
446 )
447 }
448β
449 const { getByLabelText } = render(<Parent />)
450 const inputField1 = getByLabelText('unrelated')
451 expect(inputField1).toHaveValue('John')
452 })
453β
454 it('should remap FieldGroupApi.Field validators to the correct names', () => {
455 const FieldGroupString = withFieldGroup({
456 defaultValues: { password: '', confirmPassword: '' },
457 render: function Render({ group }) {
458 return (
459 <group.Field
460 name="password"
461 validators={{
462 onChange: () => null,
463 onChangeListenTo: ['password'],
464 onBlur: () => null,
465 onBlurListenTo: ['confirmPassword'],
466 }}
467 >
468 {(field) => {
469 expect(field.options.validators?.onChangeListenTo).toStrictEqual([
470 'account.password',
471 ])
472 expect(field.options.validators?.onBlurListenTo).toStrictEqual([
473 'account.confirmPassword',
474 ])
475 return <></>
476 }}
477 </group.Field>
478 )
479 },
480 })
481β
482 const FieldGroupObject = withFieldGroup({
483 defaultValues: { password: '', confirmPassword: '' },
484 render: function Render({ group }) {
485 return (
486 <group.Field
487 name="password"
488 validators={{
489 onChange: () => null,
490 onChangeListenTo: ['password'],
491 onBlur: () => null,
492 onBlurListenTo: ['confirmPassword'],
493 }}
494 >
495 {(field) => {
496 expect(field.options.validators?.onChangeListenTo).toStrictEqual([
497 'userPassword',
498 ])
499 expect(field.options.validators?.onBlurListenTo).toStrictEqual([
500 'userConfirmPassword',
501 ])
502 return <></>
503 }}
504 </group.Field>
505 )
506 },
507 })
508β
509 const Parent = () => {
510 const form = useAppForm({
511 defaultValues: {
512 account: {
513 password: '',
514 confirmPassword: '',
515 },
516 userPassword: '',
517 userConfirmPassword: '',
518 },
519 })
520β
521 return (
522 <>
523 <FieldGroupString form={form} fields="account" />
524 <FieldGroupObject
525 form={form}
526 fields={{
527 password: 'userPassword',
528 confirmPassword: 'userConfirmPassword',
529 }}
530 />
531 </>
532 )
533 }
534β
535 render(<Parent />)
536 })
537β
538 it('should accept formId and return it', async () => {
539 function Submit() {
540 const form = useFormContext()
541β
542 return (
543 <button type="submit" form={form.formId()} data-testid="formId-target">
544 {form.formId()}
545 </button>
546 )
547 }
548β
549 function Comp() {
550 const form = useAppForm({
551 formId: 'test',
552 })
553β
554 return (
555 <form.AppForm>
556 <form
557 id={form.formId()}
558 onSubmit={(e) => {
559 e.preventDefault()
560 form.handleSubmit()
561 }}
562 ></form>
563β
564 <form.Subscribe
565 selector={(state) => state.submissionAttempts}
566 children={(submissionAttempts) => (
567 <span data-testid="formId-result">{submissionAttempts}</span>
568 )}
569 />
570β
571 <Submit />
572 </form.AppForm>
573 )
574 }
575β
576 const { getByTestId } = render(<Comp />)
577 const target = getByTestId('formId-target')
578 const result = getByTestId('formId-result')
579β
580 await user.click(target)
581 expect(result).toHaveTextContent('1')
582 })
583})