简体   繁体   English

测试 vuejs prop 默认,即玩笑中的匿名函数

[英]Testing vuejs prop default, that is anonymous function in jest

I'm trying to test the following prop in vue.js with jest:我正在尝试用 jest 测试 vue.js 中的以下道具:

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. Jest 一直告诉我我需要覆盖 onConfirm 道具的默认值,但我不知道如何做。

I've tried the following:我尝试了以下方法:

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

But both seems to be incorrect.但两者似乎都不正确。

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.我只需要模拟一个函数,然后调用我的道具 onConfirm,然后测试是否没有调用模拟函数。

Now jest says the branch has been covered.现在开玩笑说分支已经被覆盖了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM