TransWikia.com

How can set Formik isSubmitting outside of my component when testing?

Stack Overflow Asked by user3096803 on December 23, 2021

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 Answers

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')

Answered by Mike on December 23, 2021

Inside a formik child:

const form = useFormikContext()

form.setSubmitting(true)

Answered by Mordechai on December 23, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP