gpt4 book ai didi

javascript - 我如何使用 jest 在 vuejs 中测试计算属性?

转载 作者:搜寻专家 更新时间:2023-10-30 22:50:12 25 4
gpt4 key购买 nike

我仍然是单元测试的新手,我想测试当 isLinkPresent 计算属性返回图像链接并且此组件不为空时是否显示链接按钮:

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

我试图通过覆盖计算属性来测试它:

    it("renders linked button when image title has a link and is not empty", () => {
const wrapper = mount(ImageTitle, {
propsData: {
imageTitle: Object
},
computed: {
isLinkPresent() {
return this.imageTitle.link && this.imageTitle.link !== "";
}
}
});
expect(wrapper.find("a").isVisible()).toBe(true);
});

但它给了我这个错误:

[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: ""}}} 并执行 expect(wrapper.find(".bottom").exists()).toBe(true) 因为 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 |`

最佳答案

还可以选择直接在包装器提供的 View 模型(vm,参见 Vue2 view instance)上测试属性。

expect(wrapper.vm.isLinkPresent).toBe(true)

关于javascript - 我如何使用 jest 在 vuejs 中测试计算属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53763440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com