使用 react-test-renderer 测试 Formik 验证函数
Testing Formik validate function with react-test-renderer
我正在尝试通过 onChange
和 onBlur
.
使用 react-test-renderer
测试我的 validate
函数
这是一个简化的测试:
import renderer, { act } from 'react-test-renderer';
const byTypeAndName = (type, name) => elem =>
elem.type === type && elem.props.name === name;
const onSubmit = jest.fn();
const onValidate = jest.fn();
const instance = renderer.create(
<Formik
onSubmit={onSubmit}
initialValues={{
password: '',
password2: '',
}}
validate={onValidate}
>
<Form>
<Field
type="password"
name="password"
autoComplete="new-password"
required
/>
<ErrorMessage name="password" />
</Form>
</Formik>
).root;
await act(async () => {
const password = instance.find(byTypeAndName('input', 'password'));
password.props.onChange('123');
});
expect(onValidate).toBeCalled(); // fails
事实证明,onChange
和 onBlur
需要传入元素的 name
作为它们的 currentTarget
。
这可以正常工作:
await act(async () => {
const password = instance.find(byTypeAndName('input', 'password'));
password.props.onChange({
currentTarget: {
// `name` is required else Formik doesn't run validation
name: 'password',
value: '123',
},
});
});
我正在尝试通过 onChange
和 onBlur
.
react-test-renderer
测试我的 validate
函数
这是一个简化的测试:
import renderer, { act } from 'react-test-renderer';
const byTypeAndName = (type, name) => elem =>
elem.type === type && elem.props.name === name;
const onSubmit = jest.fn();
const onValidate = jest.fn();
const instance = renderer.create(
<Formik
onSubmit={onSubmit}
initialValues={{
password: '',
password2: '',
}}
validate={onValidate}
>
<Form>
<Field
type="password"
name="password"
autoComplete="new-password"
required
/>
<ErrorMessage name="password" />
</Form>
</Formik>
).root;
await act(async () => {
const password = instance.find(byTypeAndName('input', 'password'));
password.props.onChange('123');
});
expect(onValidate).toBeCalled(); // fails
事实证明,onChange
和 onBlur
需要传入元素的 name
作为它们的 currentTarget
。
这可以正常工作:
await act(async () => {
const password = instance.find(byTypeAndName('input', 'password'));
password.props.onChange({
currentTarget: {
// `name` is required else Formik doesn't run validation
name: 'password',
value: '123',
},
});
});