Javascript 如何使用jest测试vuejs中的计算属性?
对于单元测试,我仍然是新手,我想测试当Javascript 如何使用jest测试vuejs中的计算属性?,javascript,unit-testing,vue.js,jestjs,Javascript,Unit Testing,Vue.js,Jestjs,对于单元测试,我仍然是新手,我想测试当isLinkPresentcomputed属性返回图像链接且不包含此组件时,是否显示a linked按钮: <template lang="pug"> .merchandising_image_title .image(:style="`background-image: url('${imageTitle.image}');`" ) .panel .top h2 {{imageTitle.top_ti
isLinkPresent
computed属性返回图像链接且不包含此组件时,是否显示a linked按钮:
<template lang="pug">
.merchandising_image_title
.image(:style="`background-image: url('${imageTitle.image}');`" )
.panel
.top
h2 {{imageTitle.top_title}}
.line
.center
h1 {{imageTitle.center_title}}
.bottom(v-if="isLinkPresent")
a.btn.round( target='_blank' :href='imageTitle.link') Notify Me By Email
</template>
<script>
export default {
name: 'MerchandisingImageTitle',
props: {
imageTitle: Object
},
computed:{
isLinkPresent(){
return this.imageTitle.link && this.imageTitle.link !== ''
}
}
}
</script>
但它给了我一个错误:
[vue-test-utils]: find did not return a, cannot call isVisible() on empty Wrapper
13 | }
14 | });
> 15 | expect(wrapper.find("a").isVisible()).toBe(true);
| ^
16 | });
我不知道我做错了什么,任何帮助都将不胜感激
编辑:好的,所以我意识到我没有正确地传递propsData,所以我将它改为propsData:{imageTitle:{imageTitleData:{image:,top_title:,center_title:,link:}}}}}
和doexpect(wrapper.find(“.bottom”).exists()。toBe(true)
as is isVisible()主要用于v-show中,但仍然会出现以下错误:`
当图像标题有链接且不为空时,渲染链接按钮
expect(received).toBe(expected) // Object.is equality
Expected: true
Received: false
20 | }
21 | });
> 22 | expect(wrapper.find(".bottom").exists()).toBe(true);
| ^
23 | });
24 |`
首先,您应该安装组件并传递正确的道具来覆盖您的用例
let wrapper = mount(MyComponent, {
propsData: {
imageTitle: {
link: 'https://google.com'
}
}
});
然后检查链接是否按预期呈现。您可以使用exists
或findAll
并检查包装计数
expect(wrapper.find('.bottoma').exists()).toBe(true)
或
expect(wrapper.findAll('.bottoma').length.toEqual(1)
PS:个人意见,但imhoimageTitle
应命名为更直观的名称,如imageData
。
将这些作为个人道具传递也会更大。例如
还可以选择直接在包装器提供的视图模型(vm
,请参阅)上测试属性
expect(wrapper.vm.isLinkPresent).toBe(true)
什么是ImageTitle
?@ThomasEdwards它是一个道具,我在组件中将它作为对象传递,就像这样:MerchandisingGimageTitle(:ImageTitle=“imageTitleData”)
知道imageTitleData
是一个对象:imageTitleData:{图像:'',顶部标题:'',中心标题:'',链接:'}
你说你仍然得到的确切错误是什么?我的意思是在你的测试中,ImageTitle
指的是什么,而不是ImageTitle
?@ThomasEdwards是的,它指的是ImageTitle,请看一下我上面的编辑谢谢你,它工作了!我花了24小时才意识到我没有通过正确的道具,至于co不是我写的,我只是在做单元测试。再次感谢。
expect(wrapper.vm.isLinkPresent).toBe(true)