Created
July 26, 2021 19:33
-
-
Save johnrom/46b1772842a99997837903ecf5364a73 to your computer and use it in GitHub Desktop.
Test Formik
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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