首页 > 解决方案 > 模拟单元测试的 Vuex getter 会产生意想不到的结果

问题描述

我正在为 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>

这是我的组件测试套件的样子:

/* Test suite for component */

import { createLocalVue, shallowMount } from '@vue/test-utils'
import Vuex from 'vuex'
import AppFooter from '@/components/AppFooter/AppFooter'
import { mapActions, mapGetters } from 'vuex'

describe('AppFooter component', () => {   

    it('instantiates the component correctly', () => {
        const localVue = createLocalVue()
        localVue.use(Vuex)
        /* define mock getters */
        const getters = {
            resources: () => 'resources'
        }
        const store = new Vuex.Store({ getters })
        const wrapper = shallowMount(AppFooter, {
            store,
            localVue
        })

        console.log('test suite does not reach this point due to error')
    })
})

有趣的是,当我运行 Jest 测试套件时,错误如下:

在此处输入图像描述

对我来说,这似乎很奇怪,因为(考虑到组件模板的上下文),看起来resources.main属性是明确定义的,但事实resources.main.copyIco并非如此。否则,如果resources.main没有明确定义,那将是错误,而不是图片中看到的。

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

标签: unit-testingvue.jsvuejs2jestjsvuex

解决方案


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

resources.mainundefined。现在你的程序试图copyIco获得undefined. 错误是消息是正确的。它无法读取copyIcoof undefined

更好地模拟这一点的一种方法是沿着这些思路。

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

推荐阅读