Md Faysal Ahmed Akash
Md Faysal Ahmed Akash

Reputation: 336

Mock function doesn't get called when inside 'if' statement - React app testing with jest and enzyme?

I am writing a test case for my react app and I'm trying to simulate a button click with a mock function. I'm passing the mock function as a prop and I'm calling the function inside an 'if' statement but the mock function doesn't get called and the test fails but if i call the function without the 'if' statement it gets called and the test passes. Why is this happening?

Form.js

const Form = ({ text, incompleteList, setIncompleteList }) => {

  const submitTodoHandler = (e) => {
    e.preventDefault()

    if (text !== '') {
      setIncompleteList([...incompleteList, { name: text, id: Math.random() * 1000 }])
    }
  }

  return (
    <form action='' autoComplete='off'>
      <button type='submit' className='todo-button' onClick={submitTodoHandler}>
        add
      </button>
    </form>
  )
}

export default Form

Form.test.js

import Enzyme, { shallow, mount } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import Form from '../components/Form'

Enzyme.configure({ adapter: new Adapter() })

test('Form calls setIncompleteList prop on add button onClick event', () => {
  const mockfn = jest.fn()
  const wrapper = mount(<Form setIncompleteList={mockfn} />)
  wrapper.find('button').simulate('click')
  expect(mockfn).toHaveBeenCalled()
})

I'm using react 16.

Upvotes: 0

Views: 656

Answers (2)

Sarun UK
Sarun UK

Reputation: 6736

Pass value and incompleteList while mounting the component

    test('Form calls setIncompleteList prop on add button onClick event', () => {
      const mockfn = jest.fn()
      const wrapper = mount(<Form text='mock' 
incompleteList={[{name: 'sarun', id: 1001}]} setIncompleteList={mockfn} />)
      wrapper.find('button').simulate('click')
      expect(mockfn).toHaveBeenCalled()
    })

you can also set a default value for incompletelist like below so that no need to pass incompletelist while mounting the component,

const Form = ({ text, incompleteList = [], setIncompleteList }) => { 
}

Upvotes: 0

Md Faysal Ahmed Akash
Md Faysal Ahmed Akash

Reputation: 336

The problem was I did not pass the 'text' props to the form component and the comparison failed to take place that's why the mock doesn't get called and the test failed.

<Form text='mock' setIncompleteList={mockfn} />

Upvotes: 1

Related Questions