我正在尝试使用 Jest 测试一个简单的 Vue3 组件。我想评估某个文本是否被渲染。该决定取决于 bool 计算值 (isNeverShowAgain
),我想模拟该计算值。
<template>
<div :class="{ modal: true, 'is-active': showDialog }">
....
<WelcomeText />
....
</div>
</template>
<script lang="ts">
....
export default defineComponent({
name: 'WelcomeMessage',
components: { WelcomeText },
data() {
return {
/** Whether to show the message this time*/
showDialog: false,
....
};
},
beforeMount() {
//Decide whether to actually show this dialog now, before mounting it, to avoid any flicker
this.showDialog = !this.isNeverShowAgain === true;
},
....
computed: {
/** Whether the welcome message has been permanently dismissed */
isNeverShowAgain(): boolean {
return this.$store.getters.neverShowWelcomeMessageAgain;
},
},
});
</script>
如上所示,在现实世界中,这个计算值 (isNeverShowAgain
) 是从 vuex 存储属性中获取的,这就是我被卡住的地方。有很多帖子展示了如何模拟 vuex 存储,但这对我来说似乎太过分了。
如何在不模拟整个 vuex 存储的情况下模拟 isNeverShowAgain
计算值?
这是我失败的测试:
/**
* @jest-environment jsdom
* @devdoc See https://github.com/vuejs/vue-test-utils-next/issues/194#issue-689186727 about the setup with "as any"
*/
import { mount } from '@vue/test-utils';
import WelcomeMessage from '@/components/WelcomeMessage.vue';
describe('WelcomeMessage.vue', () => {
it('should display the message', () => {
const wrapper = mount(WelcomeMessage, {
computed: {
isNeverShowAgain() {
return false;
},
},
} as any);
// wrapper.vm.setComputed({ isNeverShowAgain: false }); //Deprecated and does not work
// Assert the rendered text of the component
expect(wrapper.text()).toContain('Welcome');
});
});
这是我得到的错误:
TypeError: Cannot read property 'getters' of undefined
69 | /** Whether the welcome message has been permanently dismissed */
70 | isNeverShowAgain(): boolean {
> 71 | return this.$store.getters.neverShowWelcomeMessageAgain;
| ^
72 | },
73 | },
74 | });
很明显,问题出在未模拟的 vuex 存储上,但同样,我如何模拟计算值,这首先取决于存储?
请记住,这是 Vue3 和匹配的 Jest2 测试工具,因此一些以前可用的功能现在已弃用,例如 setComputed。
我的依赖
"devDependencies": {
.....
"@types/jest": "^27.0.2",
"@vue/test-utils": "^2.0.0-rc.16",
"@vue/vue3-jest": "^27.0.0-alpha.3",
"jest": "^27.3.1",
"jest-cli": "^27.3.1",
"ts-jest": "^27.0.7",
"ts-node": "^10.4.0",
"typescript": "~4.1.5",
},
最佳答案
你不必模拟计算,但你必须像这样模拟商店:
const wrapper = mount(WelcomeMessage, {
$mocks: {
$store: {
getters: {
neverShowWelcomeMessageAgain: true
}
}
}
});
https://stackoverflow.com/questions/69939335/
相关文章:
computer-vision - 不同相机 View 之间的映射
c++ - 如何使用 Boost 在缓冲区中进行二进制序列化
python - IPywidgets 观察包裹在一个类中时不起作用
node.js - 在配置数据库时连接详细信息不可用 Digital Ocean
reactjs - “开始故事书”不被识别为内部或外部命令,
python - 如果使用 native ORM,如何避免 Django Rest API 中的 S
git - 重新启用 Visual Studio Code GitHub 身份验证
c# - 由于 XmlSerialization (sgen.exe) 无法在 Visual Stu