【问题标题】:Mocking Vuex getters for unit tests yields unexpected result模拟单元测试的 Vuex getter 会产生意想不到的结果
【发布时间】:2018-12-31 09:41:11
【问题描述】:

我正在为 VueJS 组件编写单元测试,并使用 this article 作为测试将 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-testing vue.js vuejs2 jestjs vuex


    【解决方案1】:

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

    resources.mainundefined。现在您的程序尝试获取undefinedcopyIco 属性。错误是消息是正确的。它无法读取undefinedcopyIco

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

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

    【讨论】:

      猜你喜欢
      • 2019-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-18
      • 1970-01-01
      相关资源
      最近更新 更多