gpt4 book ai didi

unit-testing - 使用 Jest 测试 Vue3 组件时如何模拟计算属性

转载 作者:行者123 更新时间:2023-12-05 04:41:53 24 4
gpt4 key购买 nike

情况

我正在尝试使用 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
}
}
}
});

关于unit-testing - 使用 Jest 测试 Vue3 组件时如何模拟计算属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69939335/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com