Skip to content

Instantly share code, notes, and snippets.

@johnrom
Created July 26, 2021 19:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnrom/46b1772842a99997837903ecf5364a73 to your computer and use it in GitHub Desktop.
Save johnrom/46b1772842a99997837903ecf5364a73 to your computer and use it in GitHub Desktop.
Test Formik
import * as React from 'react';
import {
render,
} from '@testing-library/react';
import {
Formik, useFormikContext,
} from 'formik';
import { getIn } from '../src';
// A default initializer
const initialValues = {
name: '',
age: 0,
};
// A default submit fn
const noop = () => {}
// here we wrap a test inside of a Formik instance
function renderForm(
ui,
props
) {
let injected;
const { rerender, ...rest } = render(
<Formik onSubmit={noop} initialValues={initialValues} {...props}>
{(formikProps) =>
(injected = formikProps) && ui ? ui : null
}
</Formik>
);
return {
getFormProps() {
return injected;
},
...rest,
rerender: () =>
rerender(
<Formik onSubmit={noop} initialValues={initialValues} {...props}>
{(formikProps) =>
(injected = formikProps) && ui ? ui : null
}
</Formik>
),
};
}
const YourErrorField = (props) => {
const formik = useFormikContext();
return <span className="error">{getIn(formik.errors, props.name)}</span>;
}
it('prints error', () => {
const { getFormProps, container } = renderForm(<YourErrorField name="hello" />);
const { setFieldError } = getFormProps();
setFieldError('hello', 'error')
expect(container.querySelector('.error')?.textContent).toBe("error");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment