【问题标题】:How to add unit test for a function that calls a function received in props如何为调用 props 中收到的函数的函数添加单元测试
【发布时间】:2020-01-06 04:38:58
【问题描述】:
 onSubmit = (e) => {
   e.preventDefault()
   const errors = this.validateForm()
   if (!errors) {
     const { handleSubmit } = this.props
     handleSubmit(e)
   }
 }

 <---------- unit test ---------> 

 it('calls onSubmit prop function when form is submitted', () => {
   const onSubmit = jest.fn()
   const handleSubmit = jest.fn()
   const wrapper1 = mount(<Form handleSubmit={handleSubmit} onSubmit= 
   {onSubmit} />)
   const form = wrapper1.find('form')
   form.simulate('submit')
   expect(onSubmit).toHaveBeenCalledTimes(1)
 })

 <----------- HTML ----------->

 <Form
  onSubmit={this.onSubmit}
  render={() => (
    <form onSubmit={this.onSubmit} id="submit-form">
      <div>
        <label>{countryName}</label>
      </div>
      <input type="submit" id="submit-form" className="invisible" />    
    </form>
  )}
/>

上面的代码 sn-p 是呈现 HTML 的示例,onSubmit 是用户提交表单时调用的函数。 基本上,这个组件是通用表单组件,因此 handleSubmit 是从 props 中的父组件发送的,并且通过我添加的单元测试它会生成错误 Expected mock function to have been called one time, but it was called zero times. 如果我将 handleSubmit 删除为:

it('calls onSubmit prop function when form is submitted', () => {
  const onSubmit = jest.fn()
  const wrapper1 = mount(<Form onSubmit= 
  {onSubmit} />)
  const form = wrapper1.find('form')
  form.simulate('submit')
  expect(onSubmit).toHaveBeenCalledTimes(1)
})

它会产生TypeError: handleSubmit is not a function 错误。

【问题讨论】:

    标签: reactjs unit-testing mocking jestjs enzyme


    【解决方案1】:

    问题是在测试中您正在检查组件内部根本没有使用的onSubmit

    it('calls onSubmit prop function when form is submitted', () => {
        const onSubmit = jest.fn() //not used in the component
        const handleSubmit = jest.fn()
        const wrapper1 = mount(<Form handleSubmit={handleSubmit} onSubmit={onSubmit} />)
        const form = wrapper1.find('form')
        form.simulate('submit')
        expect(onSubmit).toHaveBeenCalledTimes(1) //In component you don't use onSubmit
    })
    

    你应该测试handleSubmit的用法:

    it('calls onSubmit prop function when form is submitted', () => {
        const handleSubmit = jest.fn()
        const wrapper1 = mount(<Form handleSubmit={handleSubmit}/>)
        const form = wrapper1.find('form')
        form.simulate('submit')
        expect(handleSubmit).toHaveBeenCalledTimes(1)
    })
    

    【讨论】:

    • 我在 props 中传递了handleSubmit,正如你所看到的const wrapper1 = mount(&lt;Form handleSubmit={handleSubmit} onSubmit= {onSubmit} /&gt;)
    • 你在哪里定义onSubmit函数?在Form 组件内部还是外部?如果在 Form 组件之外,它将不会从中读取 handleSubmit 属性。
    • 在表单组件内部定义!
    • 您能否分享您的组件代码,因为我不确定它的结构?
    • @fahadtufail 我已经更新了答案。它应该解决这个问题。如果是,请标记为已解决。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-03
    • 1970-01-01
    相关资源
    最近更新 更多