Skip to content

Commit

Permalink
test: add linked onChange and onBlur tests
Browse files Browse the repository at this point in the history
  • Loading branch information
crutchcorn committed Mar 17, 2024
1 parent 564a5cf commit c7284ed
Showing 1 changed file with 81 additions and 0 deletions.
81 changes: 81 additions & 0 deletions packages/form-core/src/tests/FieldApi.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -700,4 +700,85 @@ describe('field api', () => {
await sleep(1)
expect(fn).toHaveBeenCalledTimes(1)
})

it('should run onChange on a linked field', () => {
const form = new FormApi({
defaultValues: {
password: '',
confirm_password: '',
},
})

const passField = new FieldApi({
form,
name: 'password',
})

const passconfirmField = new FieldApi({
form,
name: 'confirm_password',
validators: {
onChangeListenTo: ['password'],
onChange: ({ value, fieldApi }) => {
if (value !== fieldApi.form.getFieldValue('password')) {
return 'Passwords do not match'
}
return undefined
},
},
})

passField.mount()
passconfirmField.mount()

passField.setValue('one', { touch: true })
expect(passconfirmField.state.meta.errors).toStrictEqual(['Passwords do not match'])
passconfirmField.setValue('one', { touch: true })
expect(passconfirmField.state.meta.errors).toStrictEqual([])
passField.setValue('two', { touch: true })
expect(passconfirmField.state.meta.errors).toStrictEqual(['Passwords do not match'])
})

it('should run onBlur on a linked field', () => {
const form = new FormApi({
defaultValues: {
password: '',
confirm_password: '',
},
})

const passField = new FieldApi({
form,
name: 'password',
})

const passconfirmField = new FieldApi({
form,
name: 'confirm_password',
validators: {
onBlurListenTo: ['password'],
onBlur: ({ value, fieldApi }) => {
if (value !== fieldApi.form.getFieldValue('password')) {
return 'Passwords do not match'
}
return undefined
},
},
})

passField.mount()
passconfirmField.mount()

passField.setValue('one', { touch: true })
expect(passconfirmField.state.meta.errors).toStrictEqual([])
passField.handleBlur();
expect(passconfirmField.state.meta.errors).toStrictEqual(['Passwords do not match'])
passconfirmField.setValue('one', { touch: true })
expect(passconfirmField.state.meta.errors).toStrictEqual(['Passwords do not match'])
passField.handleBlur();
expect(passconfirmField.state.meta.errors).toStrictEqual([])
passField.setValue('two', { touch: true })
passField.handleBlur();
expect(passconfirmField.state.meta.errors).toStrictEqual(['Passwords do not match'])
})
})

0 comments on commit c7284ed

Please sign in to comment.