reactjsformikreact-test-renderer

Testing Formik validate function with react-test-renderer


I'm trying to test my validate function with react-test-renderer via onChange and onBlur.

Here is a simplified test:

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

Solution

  • It turns out that onChange and onBlur require the name of the element passed in as their currentTarget.

    This works correctly:

    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',
        },
      });
    });