使用笑话测试formik onSubmit功能不起作用

时间:2019-07-12 09:59:07

标签: reactjs jestjs enzyme formik

如何测试提交功能?

我的onSubmit处理程序(mockFunction)在稍有延迟后执行。如果我在 form.props()。onSubmit()之后紧接console.log或Expect语句,则测试将失败,因为尚未调用处理程序。

这是我的表单组件

const CreateNavItemFormInner = ({
  onSubmitNavItem,
}) => (
<Formik
    onSubmit={(values, actions) => {
      console.log('onSubmit called, calling mock function')
      onSubmitNavItem(values) 
    }}
// other code

这是我的考试

it('calls onSubmitNavItem on form submission', ()=> {
    const mockFunction = jest.fn(v => {
      console.log('inside mock function', v)
      // done()
    })

const props = {
  onSubmitNavItem: mockFunction,
  validate: jest.fn(values => {
    console.log('validating ', values)
    return {}
  }),
}
    const wrapper = mount( <CreateNavItemFormInner {...props} /> )
    const form = wrapper.find('form').first()
    form.props().onSubmit()

    console.log('after onSubmit ==> ')
    // mockFunction.mock.calls.length returns 0
    // expect(mockFunction.mock.calls.length).toBe(1) , this fails
    // expect(mockFunction).toHaveBeenCalled(), this fails too
  })

输出

console.log src/components/NavigationSettings/CreateNavItemForm/__tests__/CreateNavItemForm.test.js:26
    validating  { url: '', title: '' }

  console.log src/components/NavigationSettings/CreateNavItemForm/__tests__/CreateNavItemForm.test.js:53
    after onSubmit ==>

  console.log src/components/NavigationSettings/CreateNavItemForm/CreateNavItemFormInner.js:26
    onSubmit called, calling mock function

  console.log src/components/NavigationSettings/CreateNavItemForm/__tests__/CreateNavItemForm.test.js:18
    inside mock function { url: '', title: '' }

我已使用此链接中的第一个示例通过了测试。 https://jestjs.io/docs/en/asynchronous

但是有人可以向我解释为什么会有延迟吗? Formik的onSubmit函数是异步的吗?

0 个答案:

没有答案