Open History to see the last commit
1import { render } from '@testing-library/angular'
2import { ChangeDetectionStrategy, Component } from '@angular/core'
3import { describe, expect, it } from 'vitest'
4import { userEvent } from '@testing-library/user-event'
5import { TanStackField, injectForm } from '../src/index'
6import { sleep } from './utils'
7import type { FieldValidateAsyncFn, FieldValidateFn } from '@tanstack/form-core'
8β
9const user = userEvent.setup()
10β
11describe('TanStackFieldDirective', () => {
12 it('should allow to set default value', async () => {
13 @Component({
14 selector: 'test-component',
15 standalone: true,
16 changeDetection: ChangeDetectionStrategy.OnPush,
17 template: `
18 <ng-container [tanstackField]="form" name="firstName" #f="field">
19 <input
20 data-testid="fieldinput"
21 [value]="f.api.state.value"
22 (blur)="f.api.handleBlur()"
23 (input)="f.api.handleChange($any($event).target.value)"
24 />
25 </ng-container>
26 `,
27 imports: [TanStackField],
28 })
29 class TestComponent {
30 form = injectForm({
31 defaultValues: {
32 firstName: 'FirstName',
33 lastName: 'LastName',
34 },
35 })
36 }
37β
38 const { getByTestId } = await render(TestComponent)
39β
40 const input = getByTestId('fieldinput')
41 expect(input).toHaveValue('FirstName')
42 })
43β
44 it('should use field default value first', async () => {
45 type Person = {
46 firstName: string
47 lastName: string
48 }
49β
50 @Component({
51 selector: 'test-component',
52 standalone: true,
53 changeDetection: ChangeDetectionStrategy.OnPush,
54 template: `
55 <ng-container
56 [tanstackField]="form"
57 name="firstName"
58 defaultValue="otherName"
59 #f="field"
60 >
61 <input
62 data-testid="fieldinput"
63 [value]="f.api.state.value"
64 (blur)="f.api.handleBlur()"
65 (input)="f.api.handleChange($any($event).target.value)"
66 />
67 </ng-container>
68 `,
69 imports: [TanStackField],
70 })
71 class TestComponent {
72 form = injectForm({
73 defaultValues: {
74 firstName: 'FirstName',
75 lastName: 'LastName',
76 } as Person,
77 })
78 }
79β
80 const { getByTestId } = await render(TestComponent)
81β
82 const input = getByTestId('fieldinput')
83 expect(input).toHaveValue('otherName')
84 })
85β
86 it('should not validate on change if isTouched is false', async () => {
87 type Person = {
88 firstName: string
89 lastName: string
90 }
91 const error = 'Please enter a different value'
92β
93 @Component({
94 selector: 'test-component',
95 standalone: true,
96 changeDetection: ChangeDetectionStrategy.OnPush,
97 template: `
98 <ng-container
99 [tanstackField]="form"
100 name="firstName"
101 [validators]="{ onChange: otherValidator }"
102 #f="field"
103 >
104 <input
105 data-testid="fieldinput"
106 [value]="f.api.state.value"
107 (blur)="f.api.handleBlur()"
108 (input)="
109 f.api.setValue($any($event).target.value, {
110 dontUpdateMeta: true,
111 })
112 "
113 />
114 @for (error of f.api.getMeta().errors; track error) {
115 <p>{{ error }}</p>
116 }
117 </ng-container>
118 `,
119 imports: [TanStackField],
120 })
121 class TestComponent {
122 otherValidator: FieldValidateFn<Person, 'firstName'> = ({ value }) =>
123 value === 'other' ? error : undefined
124β
125 form = injectForm({
126 defaultValues: {
127 firstName: 'FirstName',
128 lastName: 'LastName',
129 } as Person,
130 })
131 }
132β
133 const { getByTestId, queryByText } = await render(TestComponent)
134 const input = getByTestId('fieldinput')
135 await user.type(input, 'other')
136 expect(queryByText(error)).not.toBeInTheDocument()
137 })
138β
139 it('should validate on change if isTouched is true', async () => {
140 type Person = {
141 firstName: string
142 lastName: string
143 }
144 const error = 'Please enter a different value'
145β
146 @Component({
147 selector: 'test-component',
148 standalone: true,
149 changeDetection: ChangeDetectionStrategy.OnPush,
150 template: `
151 <ng-container
152 [tanstackField]="form"
153 name="firstName"
154 [defaultMeta]="{ isTouched: true }"
155 [validators]="{ onChange: otherValidator }"
156 #f="field"
157 >
158 <input
159 data-testid="fieldinput"
160 [value]="f.api.state.value"
161 (blur)="f.api.handleBlur()"
162 (input)="f.api.handleChange($any($event).target.value)"
163 />
164 <p>{{ f.api.getMeta().errorMap?.onChange }}</p>
165 </ng-container>
166 `,
167 imports: [TanStackField],
168 })
169 class TestComponent {
170 otherValidator: FieldValidateFn<Person, 'firstName'> = ({ value }) =>
171 value === 'other' ? error : undefined
172β
173 form = injectForm({
174 defaultValues: {
175 firstName: '',
176 lastName: '',
177 } as Person,
178 })
179 }
180β
181 const { getByTestId, queryByText, getByText } = await render(TestComponent)
182β
183 const input = getByTestId('fieldinput')
184 expect(queryByText(error)).not.toBeInTheDocument()
185 await user.type(input, 'other')
186 expect(getByText(error)).toBeInTheDocument()
187 })
188β
189 it('should validate on change and on blur', async () => {
190 type Person = {
191 firstName: string
192 lastName: string
193 }
194 const onChangeError = 'Please enter a different value (onChangeError)'
195 const onBlurError = 'Please enter a different value (onBlurError)'
196β
197 @Component({
198 selector: 'test-component',
199 standalone: true,
200 changeDetection: ChangeDetectionStrategy.OnPush,
201 template: `
202 <ng-container
203 [tanstackField]="form"
204 name="firstName"
205 [defaultMeta]="{ isTouched: true }"
206 [validators]="{ onChange: onChange, onBlur: onBlur }"
207 #f="field"
208 >
209 <input
210 data-testid="fieldinput"
211 [value]="f.api.state.value"
212 [name]="f.api.name"
213 (blur)="f.api.handleBlur()"
214 (input)="
215 f.api.setValue($any($event).target.value, {
216 dontUpdateMeta: true,
217 })
218 "
219 />
220 <p>{{ f.api.getMeta().errorMap?.onChange }}</p>
221 <p>{{ f.api.getMeta().errorMap?.onBlur }}</p>
222 </ng-container>
223 `,
224 imports: [TanStackField],
225 })
226 class TestComponent {
227 onChange: FieldValidateFn<Person, 'firstName'> = ({ value }) =>
228 value === 'other' ? onChangeError : undefined
229 onBlur: FieldValidateFn<Person, 'firstName'> = ({ value }) =>
230 value === 'other' ? onBlurError : undefined
231β
232 form = injectForm({
233 defaultValues: {
234 firstName: '',
235 lastName: '',
236 } as Person,
237 })
238 }
239β
240 const { getByTestId, getByText, queryByText } = await render(TestComponent)
241 const input = getByTestId('fieldinput')
242 expect(queryByText(onChangeError)).not.toBeInTheDocument()
243 expect(queryByText(onBlurError)).not.toBeInTheDocument()
244 await user.type(input, 'other')
245 expect(getByText(onChangeError)).toBeInTheDocument()
246 await user.click(document.body)
247 expect(queryByText(onBlurError)).toBeInTheDocument()
248 })
249β
250 it('should validate async on change', async () => {
251 type Person = {
252 firstName: string
253 lastName: string
254 }
255 const error = 'Please enter a different value'
256β
257 @Component({
258 selector: 'test-component',
259 standalone: true,
260 changeDetection: ChangeDetectionStrategy.OnPush,
261 template: `
262 <ng-container
263 [tanstackField]="form"
264 name="firstName"
265 [defaultMeta]="{ isTouched: true }"
266 [validators]="{ onChangeAsync: onChangeAsync }"
267 #f="field"
268 >
269 <input
270 data-testid="fieldinput"
271 [name]="f.api.name"
272 [value]="f.api.state.value"
273 (blur)="f.api.handleBlur()"
274 (input)="f.api.handleChange($any($event).target.value)"
275 />
276 <p>{{ f.api.getMeta().errorMap?.onChange }}</p>
277 </ng-container>
278 `,
279 imports: [TanStackField],
280 })
281 class TestComponent {
282 onChangeAsync: FieldValidateAsyncFn<Person, 'firstName'> = async () => {
283 await sleep(10)
284 return error
285 }
286β
287 form = injectForm({
288 defaultValues: {
289 firstName: '',
290 lastName: '',
291 } as Person,
292 })
293 }
294β
295 const { getByTestId, getByText, findByText, queryByText } =
296 await render(TestComponent)
297 const input = getByTestId('fieldinput')
298 expect(queryByText(error)).not.toBeInTheDocument()
299 await user.type(input, 'other')
300 await findByText(error)
301 expect(getByText(error)).toBeInTheDocument()
302 })
303β
304 it('should validate async on change and async on blur', async () => {
305 type Person = {
306 firstName: string
307 lastName: string
308 }
309 const onChangeError = 'Please enter a different value (onChangeError)'
310 const onBlurError = 'Please enter a different value (onBlurError)'
311β
312 @Component({
313 selector: 'test-component',
314 standalone: true,
315 changeDetection: ChangeDetectionStrategy.OnPush,
316 template: `
317 <ng-container
318 [tanstackField]="form"
319 name="firstName"
320 [defaultMeta]="{ isTouched: true }"
321 [validators]="{
322 onChangeAsync: onChangeAsync,
323 onBlurAsync: onBlurAsync,
324 }"
325 #f="field"
326 >
327 <input
328 data-testid="fieldinput"
329 [name]="f.api.name"
330 [value]="f.api.state.value"
331 (blur)="f.api.handleBlur()"
332 (input)="f.api.handleChange($any($event).target.value)"
333 />
334 <p>{{ f.api.getMeta().errorMap?.onChange }}</p>
335 <p>{{ f.api.getMeta().errorMap?.onBlur }}</p>
336 </ng-container>
337 `,
338 imports: [TanStackField],
339 })
340 class TestComponent {
341 onChangeAsync: FieldValidateAsyncFn<Person, 'firstName'> = async () => {
342 await sleep(10)
343 return onChangeError
344 }
345β
346 onBlurAsync: FieldValidateAsyncFn<Person, 'firstName'> = async () => {
347 await sleep(10)
348 return onBlurError
349 }
350β
351 form = injectForm({
352 defaultValues: {
353 firstName: '',
354 lastName: '',
355 } as Person,
356 })
357 }
358β
359 const { getByTestId, getByText, findByText, queryByText } =
360 await render(TestComponent)
361 const input = getByTestId('fieldinput')
362β
363 expect(queryByText(onChangeError)).not.toBeInTheDocument()
364 expect(queryByText(onBlurError)).not.toBeInTheDocument()
365 await user.type(input, 'other')
366 await findByText(onChangeError)
367 expect(getByText(onChangeError)).toBeInTheDocument()
368 await user.click(document.body)
369 await findByText(onBlurError)
370 expect(getByText(onBlurError)).toBeInTheDocument()
371 })
372β
373 it('should rerender array mode field on swapFieldValues', async () => {
374 @Component({
375 selector: 'test-component',
376 standalone: true,
377 changeDetection: ChangeDetectionStrategy.OnPush,
378 template: `
379 <ng-container
380 [tanstackField]="form"
381 name="test"
382 mode="array"
383 #f="field"
384 >
385 <div data-testid="val">{{ stringify(f.api.state.value) }}</div>
386 <button
387 data-testid="swap"
388 type="button"
389 (click)="form.swapFieldValues('test', 0, 1)"
390 >
391 swap
392 </button>
393 </ng-container>
394 `,
395 imports: [TanStackField],
396 })
397 class TestComponent {
398 form = injectForm({
399 defaultValues: {
400 test: ['a', 'b'] as string[],
401 },
402 })
403 stringify = (v: unknown) => JSON.stringify(v)
404 }
405β
406 const { getByTestId } = await render(TestComponent)
407β
408 expect(getByTestId('val')).toHaveTextContent('["a","b"]')
409 await user.click(getByTestId('swap'))
410 expect(getByTestId('val')).toHaveTextContent('["b","a"]')
411 })
412})
413β
414describe('form should reset default value when resetting in onSubmit', () => {
415 it('should be able to handle async resets', async () => {
416 @Component({
417 selector: 'test-component',
418 standalone: true,
419 template: `
420 <ng-container [tanstackField]="form" name="name" #f="field">
421 <input
422 data-testid="fieldinput"
423 [value]="f.api.state.value"
424 (input)="f.api.handleChange($any($event).target.value)"
425 />
426 </ng-container>
427 <button
428 type="button"
429 (click)="form.handleSubmit()"
430 data-testid="submit"
431 >
432 submit
433 </button>
434 `,
435 imports: [TanStackField],
436 })
437 class TestComponent {
438 form = injectForm({
439 defaultValues: {
440 name: '',
441 },
442 onSubmit: ({ value }) => {
443 expect(value).toEqual({ name: 'test' })
444 this.form.reset({ name: 'test' })
445 },
446 })
447 }
448β
449 const { getByTestId } = await render(TestComponent)
450β
451 const input = getByTestId('fieldinput')
452 const submit = getByTestId('submit')
453β
454 await user.type(input, 'test')
455 await expect(input).toHaveValue('test')
456β
457 await user.click(submit)
458β
459 await expect(input).toHaveValue('test')
460 })
461})