vue3 + jest + VTU使用问题记录
1、判断dom元素中是否包含某个元素
import addEditUser from '@/views/UserManage/addUser.vue'
import ElementPlus from 'element-plus'
import { mount } from '@vue/test-utils'
describe ( 'addEditUser' , ( ) => {
const wrapper = mount ( addEditUser, {
global : {
plugins : [ ElementPlus]
}
} )
test ( '测试dom元素' , ( ) => {
expect ( wrapper. html ( ) ) . toContain ( '<span class="">保存</span>' )
expect ( wrapper. html ( ) ) . toContain ( '<span class="">取消</span>' )
} )
} )
2、获取不到dialog的body(只能获取到其header和footer)
test ( '测试dom元素' , async ( ) => {
await wrapper. vm. $nextTick ( )
console. log ( wrapper. html ( ) )
} )
3、修改组件ref、props……定义的数据
组件
< template>
< input / >
< / template>
< script setup>
import { ref, defineProps } from 'vue'
const props = defineProps ( {
title : { type : String }
} )
const isDialogAddVisible = ref ( true )
< / script>
测试文件
import userManage from '@/views/UserManage/userManage.vue'
import ElementPlus from 'element-plus'
import { mount } from '@vue/test-utils'
describe ( 'userManage ' , ( ) => {
const wrapper = mount ( userManage , {
global : {
plugins : [ ElementPlus]
}
} )
test ( '测试修改组件的数据' , async ( ) => {
wrapper. vm. isDialogAddVisible = false
await wrapper. setProps ( { title : '标题' } )
const input = wrapper. find ( 'input' )
await input. setValue ( '输入' )
} )
} )
4、判断页面中的某个函数是否被调用
import userManage from '../views/userManagement/index.vue'
import ElementPlus from 'element-plus'
import { mount } from '@vue/test-utils'
describe ( 'userManage' , ( ) => {
const wrapper = mount ( userManage, {
global : {
plugins : [ ElementPlus]
}
} )
it ( '测试页面的某个函数是否被调用' , async ( ) => {
const spyFn = jest. spyOn ( wrapper. vm, 'getTableData' )
wrapper. vm. getTableData ( )
expect ( spyFn) . toBeCalled ( )
} )
} )