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

FormField.spec.tsx

429 lines12.7 KB

1import { describe, expect, it, vi } from 'vitest'
2import { render } from 'vitest-browser-preact'
3import { useEffect, useState } from 'preact/compat'
4import { userEvent } from 'vitest/browser'
5import { useForm } from '../src'
6import type { AnyInternalFormApi } from '@tanstack/form-core/internals'
7​
8describe('Form fields', () => {
9 it('should mount the field to the dom', async () => {
10 function Component() {
11 const form = useForm({ defaultValues: { name: 'tony-hawk' } })
12 return (
13 <form.Field name="name">
14 {(field) => <span data-testid="name">{field.value}</span>}
15 </form.Field>
16 )
17 }
18​
19 const { getByTestId } = render(<Component />)
20 const input = getByTestId('name')
21​
22 await expect.element(input).toHaveTextContent('tony-hawk')
23 })
24​
25 it('does not re-register fields during unrelated parent rerenders', async () => {
26 const onMount = vi.fn()
27 const onUnmount = vi.fn()
28​
29 function Component() {
30 const [count, setCount] = useState(0)
31 const form = useForm({ defaultValues: { name: 'tony-hawk' } })
32​
33 return (
34 <>
35 <button onClick={() => setCount(count + 1)}>Rerender {count}</button>
36 <form.Field
37 name="name"
38 listeners={[
39 { triggers: ['mount'], run: onMount },
40 { triggers: ['unmount'], run: onUnmount },
41 ]}
42 >
43 {(field) => <span data-testid="name">{field.value}</span>}
44 </form.Field>
45 </>
46 )
47 }
48​
49 const { getByTestId, getByRole, unmount } = render(<Component />)
50​
51 await expect.element(getByTestId('name')).toHaveTextContent('tony-hawk')
52 expect(onMount.mock.calls.length - onUnmount.mock.calls.length).toBe(1)
53​
54 const initialMountCount = onMount.mock.calls.length
55 const initialUnmountCount = onUnmount.mock.calls.length
56​
57 const rerender = getByRole('button', { name: /Rerender/ })
58 await rerender.click()
59​
60 await expect.element(rerender).toHaveTextContent('Rerender 1')
61 expect(onMount).toHaveBeenCalledTimes(initialMountCount)
62 expect(onUnmount).toHaveBeenCalledTimes(initialUnmountCount)
63​
64 unmount()
65​
66 expect(onMount.mock.calls.length - onUnmount.mock.calls.length).toBe(0)
67 expect(onUnmount).toHaveBeenCalledTimes(initialUnmountCount + 1)
68 })
69​
70 it('should have the correct name and value', async () => {
71 function Component() {
72 const form = useForm({ defaultValues: { name: 'tony-hawk' } })
73 return (
74 <form.Field name="name">
75 {(field) => (
76 <>
77 <label htmlFor={field.name}>
78 {field.name}
79 <input
80 id={field.name}
81 value={field.value}
82 onChange={(e) => field.handleChange(e.currentTarget.value)}
83 />
84 </label>
85 </>
86 )}
87 </form.Field>
88 )
89 }
90​
91 const { getByLabelText } = render(<Component />)
92 const input = getByLabelText('name')
93 await expect.element(input).toBeInTheDocument()
94 await expect.element(input).toHaveValue('tony-hawk')
95​
96 await input.clear()
97 await userEvent.type(input, 'new-value')
98 await expect.element(input).toHaveValue('new-value')
99 })
100​
101 it('should have the correct meta when changing the field', async () => {
102 function Component() {
103 const form = useForm({ defaultValues: { name: 'tony-hawk' } })
104 return (
105 <form.Field name="name">
106 {(field) => (
107 <>
108 <label htmlFor={field.name}>
109 {field.name}
110 <input
111 id={field.name}
112 value={field.value}
113 onChange={(e) => field.handleChange(e.currentTarget.value)}
114 />
115 </label>
116 <input
117 type="checkbox"
118 data-testid="isTouched"
119 readOnly
120 checked={field.meta.isTouched}
121 />
122 <input
123 type="checkbox"
124 data-testid="isDirty"
125 readOnly
126 checked={field.meta.isDirty}
127 />
128 </>
129 )}
130 </form.Field>
131 )
132 }
133​
134 const { getByLabelText, getByTestId } = render(<Component />)
135 const input = getByLabelText('name')
136 const isTouchedCheckbox = getByTestId('isTouched')
137 const isDirtyCheckbox = getByTestId('isDirty')
138​
139 await expect.element(isTouchedCheckbox).not.toBeChecked()
140 await expect.element(isDirtyCheckbox).not.toBeChecked()
141 await userEvent.type(input, 'foo')
142 await expect.element(isTouchedCheckbox).toBeChecked()
143 await expect.element(isDirtyCheckbox).toBeChecked()
144 })
145​
146 it('should update isDefaultValue when changing back to the default value', async () => {
147 function Component() {
148 const form = useForm({ defaultValues: { name: 'tony-hawk' } })
149 return (
150 <form.Field name="name">
151 {(field) => (
152 <>
153 <label htmlFor={field.name}>
154 {field.name}
155 <input
156 id={field.name}
157 value={field.value}
158 onChange={(e) => field.handleChange(e.currentTarget.value)}
159 />
160 </label>
161 <span data-testid="isDefaultValue">
162 {String(field.meta.isDefaultValue)}
163 </span>
164 <span data-testid="isDirty">{String(field.meta.isDirty)}</span>
165 </>
166 )}
167 </form.Field>
168 )
169 }
170​
171 const { getByLabelText, getByTestId } = render(<Component />)
172 const input = getByLabelText('name')
173​
174 await expect
175 .element(getByTestId('isDefaultValue'))
176 .toHaveTextContent('true')
177 await input.clear()
178 await userEvent.type(input, 'rodney-mullen')
179 await expect
180 .element(getByTestId('isDefaultValue'))
181 .toHaveTextContent('false')
182​
183 await input.clear()
184 await userEvent.type(input, 'tony-hawk')
185 await expect
186 .element(getByTestId('isDefaultValue'))
187 .toHaveTextContent('true')
188 await expect.element(getByTestId('isDirty')).toHaveTextContent('true')
189 })
190​
191 it('does not rerender unchanged field render props when another field changes', async () => {
192 const renderCounts = {
193 first: 0,
194 middle: 0,
195 last: 0,
196 }
197​
198 function Component() {
199 const form = useForm({
200 defaultValues: {
201 first: 'first',
202 middle: 'middle',
203 last: 'last',
204 },
205 })
206​
207 return (
208 <>
209 <form.Field name="first">
210 {(field) => {
211 renderCounts.first++
212 return (
213 <label htmlFor={field.name}>
214 {field.name}
215 <input
216 id={field.name}
217 value={field.value}
218 onChange={(event) =>
219 field.handleChange(event.currentTarget.value)
220 }
221 />
222 </label>
223 )
224 }}
225 </form.Field>
226 <form.Field name="middle">
227 {(field) => {
228 renderCounts.middle++
229 return (
230 <label htmlFor={field.name}>
231 {field.name}
232 <input
233 id={field.name}
234 value={field.value}
235 onChange={(event) =>
236 field.handleChange(event.currentTarget.value)
237 }
238 />
239 </label>
240 )
241 }}
242 </form.Field>
243 <form.Field name="last">
244 {(field) => {
245 renderCounts.last++
246 return (
247 <label htmlFor={field.name}>
248 {field.name}
249 <input
250 id={field.name}
251 value={field.value}
252 onChange={(event) =>
253 field.handleChange(event.currentTarget.value)
254 }
255 />
256 </label>
257 )
258 }}
259 </form.Field>
260 </>
261 )
262 }
263​
264 const { getByLabelText } = render(<Component />)
265 const initialCounts = { ...renderCounts }
266 const middleInput = getByLabelText('middle')
267​
268 await middleInput.fill('updated')
269​
270 await expect.element(middleInput).toHaveValue('updated')
271 expect(renderCounts.first).toBe(initialCounts.first)
272 expect(renderCounts.last).toBe(initialCounts.last)
273 expect(renderCounts.middle).toBeGreaterThan(initialCounts.middle)
274 })
275​
276 it('rerenders a field when its meta changes without changing its value', async () => {
277 const renderCounts = {
278 first: 0,
279 last: 0,
280 }
281​
282 function Component() {
283 const form = useForm({
284 defaultValues: {
285 first: 'first',
286 last: 'last',
287 },
288 })
289​
290 return (
291 <>
292 <form.Field name="first">
293 {(field) => {
294 renderCounts.first++
295 return (
296 <>
297 <label htmlFor={field.name}>
298 {field.name}
299 <input
300 id={field.name}
301 value={field.value}
302 onBlur={field.handleBlur}
303 onChange={(event) =>
304 field.handleChange(event.currentTarget.value)
305 }
306 />
307 </label>
308 <span data-testid="first-blurred">
309 {String(field.meta.isBlurred)}
310 </span>
311 </>
312 )
313 }}
314 </form.Field>
315 <form.Field name="last">
316 {(field) => {
317 renderCounts.last++
318 return (
319 <label htmlFor={field.name}>
320 {field.name}
321 <input
322 id={field.name}
323 value={field.value}
324 onChange={(event) =>
325 field.handleChange(event.currentTarget.value)
326 }
327 />
328 </label>
329 )
330 }}
331 </form.Field>
332 </>
333 )
334 }
335​
336 const { getByLabelText, getByTestId } = render(<Component />)
337 const initialCounts = { ...renderCounts }
338​
339 const firstInput = getByLabelText('first')
340 await firstInput.click()
341 await userEvent.tab()
342​
343 await expect.element(getByTestId('first-blurred')).toHaveTextContent('true')
344 expect(renderCounts.first).toBeGreaterThan(initialCounts.first)
345 expect(renderCounts.last).toBe(initialCounts.last)
346 })
347​
348 it('should recreate mounted fields after form reset', async () => {
349 function Component() {
350 const form = useForm({ defaultValues: { name: 'tony-hawk' } })
351 return (
352 <>
353 <form.Field name="name">
354 {(field) => (
355 <label htmlFor={field.name}>
356 {field.name}
357 <input
358 id={field.name}
359 value={field.value}
360 onChange={(e) => field.handleChange(e.currentTarget.value)}
361 />
362 </label>
363 )}
364 </form.Field>
365 <button onClick={() => form.reset()} data-testid="reset">
366 Reset
367 </button>
368 </>
369 )
370 }
371​
372 const { getByLabelText, getByTestId } = render(<Component />)
373 const input = getByLabelText('name')
374​
375 await input.clear()
376 await userEvent.type(input, 'before-reset')
377 await expect.element(input).toHaveValue('before-reset')
378​
379 await getByTestId('reset').click()
380 await expect.element(input).toHaveValue('tony-hawk')
381​
382 await input.clear()
383 await userEvent.type(input, 'after-reset')
384 await expect.element(input).toHaveValue('after-reset')
385 })
386​
387 it('should remove unused field nodes', async () => {
388 const formApi = { current: null as AnyInternalFormApi | null }
389​
390 function Component() {
391 const [show, setShow] = useState(true)
392 const form = useForm({ defaultValues: { foo: { bar: 'Value' } } })
393​
394 useEffect(() => {
395 formApi.current = form as never
396 })
397​
398 return (
399 <>
400 {show && (
401 <form.Field name="foo.bar">
402 {({ value }) => <span data-testid="field">{value}</span>}
403 </form.Field>
404 )}
405 <button onClick={() => setShow(false)} data-testid="off">
406 Turn off
407 </button>
408 </>
409 )
410 }
411​
412 const { getByTestId } = render(<Component />)
413 const field = getByTestId('field')
414​
415 await expect.element(field).toBeInTheDocument()
416 // Field exists before unmount
417 expect(formApi.current?._tryGetFieldApi('foo.bar')).not.toBeNull()
418​
419 await getByTestId('off').click()
420​
421 await expect.element(field).not.toBeInTheDocument()
422 await vi.waitFor(
423 () => {
424 expect(formApi.current?._tryGetFieldApi('foo.bar')).toBeNull()
425 },
426 { interval: 50, timeout: 500 },
427 )
428 })
429})