Ad

How To Add Unit Test For A Function That Calls A Function Received In Props

- 1 answer

 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>
  )}
/>

Above code snippet is the example of the HTML being rendered and onSubmit is the function that is being called when user submits the form. Basically, this component is generic form component thus handleSubmit is sent from the parent component in props and with the unit test that I have added it generates the error Expected mock function to have been called one time, but it was called zero times. And if I remove handleSubmit as:

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

it generates TypeError: handleSubmit is not a function error.

Ad

Answer

The issue is that in test you are checking onSubmit which is not used at all inside the component:

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

You should test usage of 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)
})
Ad
source: stackoverflow.com
Ad