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

with-form.spec.ts

75 lines2.1 KB

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