简体   繁体   English

测试时如何在我的组件之外设置 Formik isSubmitting?

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

I have stateful functional component with a Formik form that renders different content based on the value of isSubmitting.我有一个带有 Formik 表单的有状态功能组件,它根据 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?如何在我的测试中设置 Formik 表单上 isSubmitting 的值? I want to be able to test the structure of the page while it's submitting.我希望能够在提交时测试页面的结构。

Inside a formik child:在一个formik子里面:

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).通常对于测试,您会操纵 UI 并查看结果,而不是尝试操纵组件的内部(从 UI 的角度来看,它应该被视为一个黑匣子)。 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.推荐- 模拟单击提交并查看 dom 的样子。 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不推荐- 模拟 Formik 上下文
// pseudo code with enyzme
import { useFormikContext } from 'formik'

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

expect(wrapper.find('div').text()).toContain('show this on submitting')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM