【发布时间】:2026-01-23 00:50:01
【问题描述】:
如何使用 Jest 在我的父组件上测试以下 v-if?
家长:
<div class="systemIsUp" v-if="systemStatus == true">
foo
</div>
<div class="systemIsDown" v-else>
bar
</div>
<script>
export default {
name: 'File Name',
data () {
return {
systemStatus: null,
}
},
</script>
这是我当前的设置,用于测试当我更改 systemStatus 变量的值时这些 div 是否呈现 单元测试:
import { shallowMount } from '@vue/test-utils'
import FileName from 'path'
describe('FileName', () => {
//Declare wrapper for this scope
const wrapper = shallowMount(FileName)
it('Should display message saying that the system is down if "systemStatus" data variable is false', () => {
expect(wrapper.html().includes('.systemIsDown')).toBe(false)
wrapper.setData({ systemStatus: false})
expect(wrapper.html().includes('.systemIsDown')).toBe(true)
});
});
我尝试使用 contains 和 toContain 代替 includes 但仍然无法使其工作,Jest 返回以下内容:
expect(received).toBe(expected) // Object.is equality
Expected: true
Received: false
expect(wrapper.html().includes('.systemIsDown')).toBe(false)
wrapper.setData({ systemStatus: false })
expect(wrapper.html().includes('.systemIsDown')).toBe(true)
^
显然,它根本看不到 systemIsDown div,并且认为它不存在,因此为什么第一个期望会通过,但是当 systemStatus 变量更新时,我怎样才能让它看到 div? 谢谢
【问题讨论】:
-
.html().includes(text)不会将text视为选择器,它只是在字符串中搜索。看看wrapper.html()到底给了你什么。 -
我知道 wrapper.html() 将返回 HTML 输入的字符串版本,但是如果使用 wrapper.html()).toContain('.systemIsDown' ) 因为我得到以下信息: 预期的子字符串:“.systemIsDown” 收到的字符串:“" 即v-else下的完整东西而
'<div class="systemIsDown">bar</div>'.includes('.systemIsDown')是假的,因为它不是 CSS 选择器。它只是在寻找文字子字符串。如果您想使用基于 HTML 的断言,请不要将其展平为字符串。好的,我更改了断言,现在是:let division = wrapper.html()expect(division.includes("systemIsDown")).toBe(true)发现 div 很好,但是当我检查相反的版本 (systemIsUp) 我的wrapper.setData({ systemStatus: true })没有改变数据变量,断言之间是否存在数据泄露?
标签: html unit-testing vue.js vuejs2 jestjs