Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vue.js/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 为单元测试模拟Vuex getter会产生意外的结果_Unit Testing_Vue.js_Vuejs2_Jestjs_Vuex - Fatal编程技术网

Unit testing 为单元测试模拟Vuex getter会产生意外的结果

Unit testing 为单元测试模拟Vuex getter会产生意外的结果,unit-testing,vue.js,vuejs2,jestjs,vuex,Unit Testing,Vue.js,Vuejs2,Jestjs,Vuex,我正在为VueJS组件编写单元测试,并将其用作测试依赖Vuex存储的组件的参考。以下是相关组件的相关部分: <!-- COMPONENT --> <template> <div> {{ resources.main.copyIco }} {{ resources.main.rights }} {{ resources.main.read }} </div> </template> <script&g

我正在为VueJS组件编写单元测试,并将其用作测试依赖Vuex存储的组件的参考。以下是相关组件的相关部分:

<!-- COMPONENT -->

<template>
    <div>
      {{ resources.main.copyIco }} {{ resources.main.rights }} {{ resources.main.read }}
    </div>
</template>

<script>
  import { mapActions, mapGetters } from 'vuex'

  export default {
      computed: {
          ...mapGetters({
              resources: 'resources'
          })
      },
      methods: {
          ...mapActions({
              dispatchAction: 'dispatchAction'
          })
      }
   }
</script>
有趣的是,当我运行Jest测试套件时,错误如下所示:

对我来说,这似乎很奇怪,因为(考虑到组件模板的上下文),它看起来像
resources.main
属性定义得很好,但
resources.main.copyIco
不是。否则,如果
resources.main
没有很好地定义,那么这将是错误,而不是图片中显示的错误


简而言之,为什么会根据组件和套件的设置方式发生此错误?是否需要在组件中重新定义映射getter?

在您的示例中,getter只是返回一个名为
resources
的字符串,该字符串没有
main
属性。这与Vue无关

resources.main
未定义的
。现在,您的程序尝试获取
undefined
copyIco
属性。错误是消息是正确的。它无法读取未定义的
copyIco

一种更好的嘲弄方式是沿着这些思路

const getters = {
    resources: () => ({ main: { copyIco: 'something', rights: 'rights'}})
}
const getters = {
    resources: () => ({ main: { copyIco: 'something', rights: 'rights'}})
}