Skip to content

Instantly share code, notes, and snippets.

@johnrom
Created July 26, 2021 19:54
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/69a9d91a1f631543486347edf5638cec to your computer and use it in GitHub Desktop.
Save johnrom/69a9d91a1f631543486347edf5638cec to your computer and use it in GitHub Desktop.
import * as React from 'react';
import * as formik from 'formik';
jest.mock('formik');
it('prints error', () => {
formik.useFormikContext.mockResolvedValue({ errors: { hello: '' }});
const { container, rerender } = render(<Formik initialValues={{ hello: '' }}><YourErrorField name="hello" /></Formik>);
expect(container.querySelector('.error')?.textContent).toBe('');
formik.useFormikContext.mockResolvedValue({ errors: { hello: 'error' }});
rerender();
expect(container.querySelector('.error')?.textContent).toBe('');
});
// in your actual component
import { getIn, useFormikContext } from 'formik';
const YourErrorField = (props) => {
const formik = useFormikContext();
return <span className="error">{getIn(formik.errors, props.name)}</span>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment