unit-testing - 模拟单元测试的 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 吗?
解决方案
在您的示例中,您的 getter 只是返回一个名为resources
且没有main
属性的字符串。这与 Vue 无关。
resources.main
是undefined
。现在你的程序试图copyIco
获得undefined
. 错误是消息是正确的。它无法读取copyIco
of undefined
。
更好地模拟这一点的一种方法是沿着这些思路。
const getters = {
resources: () => ({ main: { copyIco: 'something', rights: 'rights'}})
}
推荐阅读
- c# - 尝试创建多个任务并并行运行它们时无法将 void 分配给隐式类型的变量
- java - 在 Tomcat 服务器中记录 Slf4j 以获取 cosole 日志
- azure - Azure:创建没有服务 URL 的新 API 管理服务
- javascript - react-scripts babel scripts 错误在本地反应应用程序上使用纱线运行
- visual-studio-code - CMake中是否有可能不扫描特定文件夹?
- c - 使用clang而不是gcc链接成功(Debian Bullseye amd64上的-llzma)
- javascript - 如何使用 node-gyp 构建 python?
- swift - 从 Swift 包中加载字体
- java - SnakeYaml 输出 yaml 与转储 yaml 不匹配
- javascript - 无法理解为什么 JS 代码不在 JS Bin 中运行