-
-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathField.test.tsx
More file actions
92 lines (78 loc) · 2.74 KB
/
Copy pathField.test.tsx
File metadata and controls
92 lines (78 loc) · 2.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import { fireEvent, screen, waitFor } from '@testing-library/dom';
import { flushSync } from 'hono/jsx/dom';
import type { JSX } from 'hono/jsx/jsx-runtime';
import * as v from 'valibot';
import { describe, expect, test, vi } from 'vitest';
import { useForm } from '../../hooks/index.ts';
import type { FieldStore } from '../../types/index.ts';
import { renderHono } from '../../vitest/render.tsx';
import { Field } from './Field.tsx';
const schema = v.object({ name: v.string() });
type FormSchema = typeof schema;
describe('Field', () => {
test('should render JSX returned from children', () => {
function Test(): JSX.Element {
const form = useForm({ schema });
return (
<Field of={form} path={['name']}>
{() => <span data-testid="content">hello</span>}
</Field>
);
}
renderHono(<Test />);
expect(screen.getByTestId('content')).toHaveTextContent('hello');
});
test('should invoke children with the field store', () => {
const renderProp = vi.fn<
(field: FieldStore<FormSchema, ['name']>) => JSX.Element
>(() => <span />);
function Test(): JSX.Element {
const form = useForm({ schema, initialInput: { name: 'John' } });
return (
<Field of={form} path={['name']}>
{renderProp}
</Field>
);
}
renderHono(<Test />);
expect(renderProp).toHaveBeenCalled();
const field = renderProp.mock.lastCall![0];
expect(field.path).toEqual(['name']);
expect(field.input).toBe('John');
expect(field.props.name).toBe('["name"]');
expect(typeof field.props.onChange).toBe('function');
});
test('should re-render when the field store updates', async () => {
function Test(): JSX.Element {
const form = useForm({ schema, initialInput: { name: 'initial' } });
return (
<Field of={form} path={['name']}>
{(field) => (
<>
<input
data-testid="input"
{...field.props}
value={field.input ?? ''}
/>
<span data-testid="dirty">{String(field.isDirty)}</span>
</>
)}
</Field>
);
}
renderHono(<Test />);
const input = screen.getByTestId('input') as HTMLInputElement;
const dirty = screen.getByTestId('dirty');
expect(input.value).toBe('initial');
expect(dirty).toHaveTextContent('false');
// hono/jsx maps the `onChange` prop to a native `input` listener, the
// same normalization React applies for its synthetic `onChange`.
flushSync(() => {
fireEvent.input(input, { target: { value: 'changed' } });
});
await waitFor(() => {
expect(input.value).toBe('changed');
expect(dirty).toHaveTextContent('true');
});
});
});