How can set Formik isSubmitting outside of my component when testing?
Inside a formik child:
const form = useFormikContext()form.setSubmitting(true)
Typically for testing, you'd manipulate the UI and see the result instead of trying to manipulate the internals of the component (which should be considered a black box from the UI's perspective). This ensures that your tests are valid verifications of real user interactions. In reality, there are sometimes reasons to be a little looser with the rules and it's up to you and your use case to determine what value you're trying to derive from the tests.
So there are two approaches:
- Recommended - Simulate clicking the submit and see what the dom looks like. Something like this (depending on your framework)
// pseudo code with enzymewrapper.find('button').simulate('click')expect(wrapper.find('div').text()).toContain('show this on submitting')
- Not recommended - Mock the Formik context
// pseudo code with enyzmeimport { useFormikContext } from 'formik'useFormikContext.mockReturnValue({ ...mockedContextObject, isSubmitting: true,})expect(wrapper.find('div').text()).toContain('show this on submitting')