首页 > 解决方案 > Vue,如何测试子组件(通过 v-show 显示)是否可见

问题描述

我试图弄清楚如何测试(使用 vue test utils & jest)子组件(通过 显示v-show)当前是否可见(与子组件的内容无关)。

我的 vue html 代码如下所示:

<ChildComponent v-show="isShowing"/>

我不知道如何测试它。我遇到了这个:https ://github.com/vuejs/vue-test-utils/issues/327#issuecomment-355501127然而,wrapper.findComponent(...).hasStyle is not a function.

我能想到的最接近的是测试布尔值:

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

我知道如何测试它是否正在使用v-if

expect(wrapper.findComponent(ChildComponent).exists()).toBe(true) //it is conditionally rendered
expect(wrapper.findComponent(ChildComponent).exists()).toBe(false) //it is not conditionally rendered

谁能指出我正确的方向?提前致谢!

标签: vue.jsjestjsvue-componentvue-test-utils

解决方案


有一种方法可以使用isVisible方法进行测试。

isVisible()方法检查是否,display:none它也可以测试visibility:hiddenopacity :0

这是您的代码示例:

expect(wrapper.findComponent(ChildComponent).isVisible()).toBe(true)

如果该组件是主要包装器,则使用如下:

expect(wrapper.isVisible()).toBe(true)

推荐阅读