【发布时间】:2021-03-16 17:55:06
【问题描述】:
在 Jest 和 Vue Test Utils 的帮助下,我刚刚开始使用 Vue 测试。
我试图在我的 Jest 测试文件中挂载一个名为 DateComponent.vue 的组件,但是在运行测试时它会抛出一个错误
TypeError: Cannot read property 'key' of undefined
安装其他组件似乎工作正常,我可以毫无问题地测试它们,但这个似乎有一些问题。
<template>
<v-menu
v-model="dateMenu"
:close-on-content-click="false"
:nudge-right="40"
transition="scale-transition"
offset-y
min-width="290px"
>
<template v-slot:activator="{ on }">
<v-text-field
v-model="value[field.key]"
label=""
readonly
v-on="on"
></v-text-field>
</template>
<v-date-picker v-model="value[field.key]" @input="dateMenu = false" locale='de-de'></v-date-picker>
</v-menu>
</template>
<script>
export default {
props: ['value', 'field'],
data: () => ({
dateMenu: false
}),
mounted: function () {
},
methods: {
},
filters: {
}
}
</script>
这就是我安装组件的方式:
import { mount } from '@vue/test-utils'
import DateComponent from './components/DateComponent'
const wrapper = mount(DateComponent)
问题似乎出在<v-text-field> 和<v-date-picker>,特别是v-model="value[field.key]",但我没有足够的经验来弄清楚发生了什么。
非常感谢
编辑
我是如何解决的:
const wrapper = mount(TestComponent, {
propsData: {
field: {
},
value: {
}
}
})
当我挂载 TestComponent 时,我将它的 propsData 和 data 设置为空数据
【问题讨论】:
-
其实你可以在不需要担心嵌套组件的地方存根
<v-text-field> & <v-date-picker>。查看this link 了解更多信息
标签: unit-testing vue.js jestjs vue-component vue-test-utils