Skip to content

Commit

Permalink
test: add sync test for React linked fields
Browse files Browse the repository at this point in the history
  • Loading branch information
crutchcorn committed Mar 18, 2024
1 parent ab49764 commit 250a839
Showing 1 changed file with 72 additions and 0 deletions.
72 changes: 72 additions & 0 deletions packages/react-form/src/tests/useField.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -687,4 +687,76 @@ describe('useField', () => {
await user.click(await findByText('Submit'))
expect(fn).toHaveBeenCalledWith({ people: [{ name: 'John', age: 0 }] })
})

it('should handle sync linked fields', async () => {
const fn = vi.fn()
function Comp() {
const form = useForm({
defaultValues: {
password: '',
confirm_password: '',
},
onSubmit: ({ value }) => fn(value),
})

return (
<div>
<form.Field name="password">
{(field) => {
return (
<div>
<label>
<div>Password</div>
<input
value={field.state.value}
onChange={(e) => field.handleChange(e.target.value)}
/>
</label>
</div>
)
}}
</form.Field>
<form.Field
name="confirm_password"
validators={{
onChangeListenTo: ['password'],
onChange: ({ value, fieldApi }) => {
if (value !== fieldApi.form.getFieldValue('password')) {
return 'Passwords do not match'
}
return undefined
},
}}
>
{(field) => {
return (
<div>
<label>
<div>Confirm Password</div>
<input
value={field.state.value}
onChange={(e) => field.handleChange(e.target.value)}
/>
</label>
{field.state.meta.errors.map((err) => {
return <div key={err?.toString()}>{err}</div>
})}
</div>
)
}}
</form.Field>
</div>
)
}

const { findByLabelText, queryByText, findByText } = render(<Comp />)

const passwordInput = await findByLabelText('Password')
const confirmPasswordInput = await findByLabelText('Confirm Password')
await user.type(passwordInput, 'password')
await user.type(confirmPasswordInput, 'password')
expect(queryByText('Passwords do not match')).not.toBeInTheDocument()
await user.type(confirmPasswordInput, '1')
expect(await findByText('Passwords do not match')).toBeInTheDocument()
})
})

0 comments on commit 250a839

Please sign in to comment.