html - 使用 Jest 对 V-If 进行单元测试
问题描述
如何使用 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而不是包含但仍然无法使其工作,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?谢谢
解决方案
更改了断言以查找特定的 CSS 选择器,如下所示:
wrapper.setData({ systemStatus: false})
expect(wrapper.find(".systemIsDown")).toBeTruthy()