Unit testing Jest测试Vue组件抛出错误“;无法读取未定义的';键'&引用;

Unit testing Jest测试Vue组件抛出错误“;无法读取未定义的';键'&引用;,unit-testing,vue.js,jestjs,vue-component,vue-test-utils,Unit Testing,Vue.js,Jestjs,Vue Component,Vue Test Utils,在Jest和Vue测试UTIL的帮助下,我刚刚开始Vue测试 我试图在Jest测试文件中挂载名为DateComponent.vue的组件,但运行测试时会抛出错误 TypeError: Cannot read property 'key' of undefined 安装其他组件似乎工作正常,我可以毫无问题地测试它们,但这一个似乎有一些问题 <template> <v-menu v-model="dateMenu" :clo

在Jest和Vue测试UTIL的帮助下,我刚刚开始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>
问题似乎在
中,特别是
v-model=“value[field.key]”
中,但我没有足够的经验来了解到底发生了什么

非常感谢

编辑

我是如何修复的:

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

当我安装TestComponent时,我将其propsData和data设置为空数据

您的问题是当您尝试访问
v-model=“value[field.key]”
时,可能您没有将
字段
prop传递给您的组件,因此,它将是
未定义的
,并且是错误的原因


此外,您不应该在道具中绑定
v-model
,如果它是静态值,请使用
:value

嘿,谢谢您的回答!如何将字段prop传递给组件?@Trivo您可以在mount方法中传递第二个参数,一个名为propsData的对象,其中包含您需要的props。在这里阅读更多!实际上,您可以在不需要担心嵌套组件的地方存根
&
。查看更多信息
const wrapper = mount(TestComponent, {
  propsData: {
    field: {
    },
    value: {
    }
  }
})