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

app-field.spec.ts

73 lines1.9 KB

1import { render } from '@testing-library/angular'
2import { ChangeDetectionStrategy, Component, input } from '@angular/core'
3import { describe, expect, it } from 'vitest'
4import {
5 TanStackAppField,
6 TanStackField,
7 injectField,
8 injectForm,
9} from '../src/index'
10​
11describe('TanStackAppField', () => {
12 it('should render a field with the correct label and default value', async () => {
13 @Component({
14 selector: 'app-text-field',
15 changeDetection: ChangeDetectionStrategy.OnPush,
16 standalone: true,
17 template: `
18 <label [for]="field.api.name">{{ label() }}</label>
19 <input
20 [id]="field.api.name"
21 [name]="field.api.name"
22 [value]="field.api.state.value"
23 (blur)="field.api.handleBlur()"
24 (input)="field.api.handleChange($any($event).target.value)"
25 />
26 `,
27 })
28 class AppTextField {
29 label = input.required<string>()
30 field = injectField<string>()
31 }
32​
33 @Component({
34 selector: 'app-root',
35 standalone: true,
36 changeDetection: ChangeDetectionStrategy.OnPush,
37 imports: [TanStackField, TanStackAppField, AppTextField],
38 template: `
39 <form (submit)="handleSubmit($event)">
40 <app-text-field
41 label="Last name:"
42 tanstack-app-field
43 [tanstackField]="form"
44 name="lastName"
45 />
46 </form>
47 `,
48 })
49 class AppComponent {
50 form = injectForm({
51 defaultValues: {
52 firstName: '',
53 lastName: 'Doe',
54 },
55 onSubmit({ value }) {
56 console.log(value)
57 },
58 })
59​
60 handleSubmit(event: SubmitEvent) {
61 event.preventDefault()
62 event.stopPropagation()
63 this.form.handleSubmit()
64 }
65 }
66​
67 const { getByLabelText } = await render(AppComponent)
68​
69 const ourInput = getByLabelText('Last name:')
70 expect(ourInput).toBeInTheDocument()
71 expect(ourInput).toHaveValue('Doe')
72 })
73})