【问题标题】:Jest Testing Vue Component throws Error "cannot read undefined 'key'..."开玩笑测试 Vue 组件抛出错误“无法读取未定义的'key'...”
【发布时间】: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)

问题似乎出在&lt;v-text-field&gt; 和&lt;v-date-picker&gt;,特别是v-model="value[field.key]",但我没有足够的经验来弄清楚发生了什么。

非常感谢

编辑

我是如何解决的:

const wrapper = mount(TestComponent, {
  propsData: {
    field: {
    },
    value: {
    }
  }
})

当我挂载 TestComponent 时,我将它的 propsData 和 data 设置为空数据

【问题讨论】:

  • 其实你可以在不需要担心嵌套组件的地方存根&lt;v-text-field&gt; &amp; &lt;v-date-picker&gt;。查看this link 了解更多信息

标签: unit-testing vue.js jestjs vue-component vue-test-utils


【解决方案1】:

您的问题是当您尝试访问 v-model="value[field.key]" 时,可能您没有将 field 属性传递给您的组件,因此,它将是 undefined 和您的错误的原因。

另外,你不应该在 prop 中绑定 v-model,如果它是静态值,请改用 :value

【讨论】:

  • 您好,谢谢您的回答!如何将字段道具传递给组件?
  • @Trivo 您可以在 mount 方法中传递第二个参数,一个名为 propsData 的对象,其中包含您需要的道具。在这里阅读更多! vue-test-utils.vuejs.org/api/options.html#propsdata
猜你喜欢
  • 2019-08-08
  • 2023-03-03
  • 2017-10-18
  • 2020-03-21
  • 1970-01-01
  • 2020-06-26
  • 2017-07-30
  • 2017-09-19
  • 2017-11-01
相关资源
最近更新 更多