Testing vuejs prop default, that is anonymous function in jest

Viewed 757

I'm trying to test the following prop in vue.js with jest:

export default {
  name: 'my-component',
  props: {
    onConfirm: {
      type: Function,
      default: () => {}
    },
  }
}

Jest keeps telling my that I need to cover default value of the onConfirm prop, but I have no clue how to.

I've tried the following:

expect(wrapper.vm.onConfirm).toBe(() => {})
expect(wrapper.vm.onConfirm).toBe(Function)

But both seems to be incorrect.

2 Answers

Try this:

expect(wrapper.props().onConfirm.name).toBe('default')

If it is a function it will have a name prop and in this case, the name would be the default.

After some more trial and error, I finally found the solution.

it('handles onConfirm default correct', async () => {
  const fn = jest.fn()
  wrapper.vm.confirm()
  expect(fn).toHaveBeenCalledTimes(0)
})

I simply had to mock a function, and call my prop onConfirm, and test if the mock function wasn't called.

Now jest says the branch has been covered.

Related