7

I have stateful functional component with a Formik form that renders different content based on the value of isSubmitting.

const MyPage: FunctionComponent<Props> = ({propOne, propTwo}) => {
  <Formik ...>
  ...
  {isSubmitting ? (
      <div>show this on submitting</div>
    ) : (
      <div>show this when not</div>
    )}
  </Formik>
};

How can I set the value of isSubmitting on the Formik form from my tests? I want to be able to test the structure of the page while it's submitting.

2 Answers2

1

Inside a formik child:

const form = useFormikContext()

form.setSubmitting(true)
Mordechai
  • 15,437
  • 2
  • 41
  • 82
0

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:

  1. Recommended - Simulate clicking the submit and see what the dom looks like. Something like this (depending on your framework)
// pseudo code with enzyme
wrapper.find('button').simulate('click')

expect(wrapper.find('div').text()).toContain('show this on submitting')
  1. Not recommended - Mock the Formik context
// pseudo code with enyzme
import { useFormikContext } from 'formik'

useFormikContext.mockReturnValue({
  ...mockedContextObject,
  isSubmitting: true,
})

expect(wrapper.find('div').text()).toContain('show this on submitting')
Mike
  • 346
  • 2
  • 8
  • in my case, isSubmitting is true when I first submit the form. but after the API request I mocked resolved, the isSubmitting is set to false again. i need the state when the isSubmitting is true. – principiorum Jul 20 '20 at 02:30
  • This can happen for a few reasons depending on the scope of your tests, which rendering approach (enzyme, testing-library, react-dom/test-utils etc.) you're using, and how you're testing. You might need to use [act](https://reactjs.org/docs/test-utils.html#act), you might not be mocking the return value at the right place so it doesn't get returned like you think it should, you might have logic in your component that's updating things automatically etc. It's hard to say without seeing more code, but those are some places you can look. – Mike Jul 20 '20 at 15:07