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

createFormHook.test.tsx

115 lines2.7 KB

1import { describe, expect, it } from 'vitest'
2import { render } from '@testing-library/react'
3import { formOptions } from '@tanstack/form-core'
4import { createFormHook, createFormHookContexts } from '../src'
5​
6const { fieldContext, useFieldContext, formContext, useFormContext } =
7 createFormHookContexts()
8​
9function TextField({ label }: { label: string }) {
10 const field = useFieldContext<string>()
11 return (
12 <label>
13 <div>{label}</div>
14 <input
15 value={field.state.value}
16 onChange={(e) => field.handleChange(e.target.value)}
17 />
18 </label>
19 )
21​
22function SubscribeButton({ label }: { label: string }) {
23 const form = useFormContext()
24 return (
25 <form.Subscribe selector={(state) => state.isSubmitting}>
26 {(isSubmitting) => <button disabled={isSubmitting}>{label}</button>}
27 </form.Subscribe>
28 )
30​
31const { useAppForm, withForm } = createFormHook({
32 fieldComponents: {
33 TextField,
34 },
35 formComponents: {
36 SubscribeButton,
37 },
38 fieldContext,
39 formContext,
40})
41​
42describe('createFormHook', () => {
43 it('should allow to set default value', () => {
44 type Person = {
45 firstName: string
46 lastName: string
47 }
48​
49 function Comp() {
50 const form = useAppForm({
51 defaultValues: {
52 firstName: 'FirstName',
53 lastName: 'LastName',
54 } as Person,
55 })
56​
57 return (
58 <>
59 <form.AppField
60 name="firstName"
61 children={(field) => <field.TextField label="Testing" />}
62 />
63 </>
64 )
65 }
66​
67 const { getByLabelText } = render(<Comp />)
68 const input = getByLabelText('Testing')
69 expect(input).toHaveValue('FirstName')
70 })
71​
72 it('should handle withForm types properly', () => {
73 const formOpts = formOptions({
74 defaultValues: {
75 firstName: 'John',
76 lastName: 'Doe',
77 },
78 })
79​
80 const ChildForm = withForm({
81 ...formOpts,
82 // Optional, but adds props to the `render` function outside of `form`
83 props: {
84 title: 'Child Form',
85 },
86 render: ({ form, title }) => {
87 return (
88 <div>
89 <p>{title}</p>
90 <form.AppField
91 name="firstName"
92 children={(field) => <field.TextField label="First Name" />}
93 />
94 <form.AppForm>
95 <form.SubscribeButton label="Submit" />
96 </form.AppForm>
97 </div>
98 )
99 },
100 })
101​
102 const Parent = () => {
103 const form = useAppForm({
104 ...formOpts,
105 })
106​
107 return <ChildForm form={form} title={'Testing'} />
108 }
109​
110 const { getByLabelText, getByText } = render(<Parent />)
111 const input = getByLabelText('First Name')
112 expect(input).toHaveValue('John')
113 expect(getByText('Testing')).toBeInTheDocument()
114 })
115})