0

我正在尝试使用via和测试我的validate功能。react-test-rendereronChangeonBlur

这是一个简化的测试:

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
4

1 回答 1

0

事实证明,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',
    },
  });
});
于 2020-05-06T00:06:09.243 回答