【发布时间】:2022-10-05 20:49:15
【问题描述】:
使用vue-test-utils来测试使用pinia的组件,需要修改pinia中存储的state的值,但是尝试了很多方法都无济于事。原始组件和存储文件如下。
// HelloWorld.vue
<template>
<h1>{{ title }}</h1>
</template>
<script>
import { useTestStore } from \"@/stores/test\";
import { mapState } from \"pinia\";
export default {
name: \"HelloWorld\",
computed: {
...mapState(useTestStore, [\"title\"]),
},
};
</script>
// @/stores/test.js
import { defineStore } from \"pinia\";
export const useTestStore = defineStore(\"test\", {
state: () => {
return { title: \"hhhhh\" };
},
});
已尝试以下方法。
- 将组件内使用的store导入到测试代码中直接进行修改,但修改不会影响组件。
// test.spec.js import { mount } from \"@vue/test-utils\"; import { createTestingPinia } from \"@pinia/testing\"; import HelloWorld from \"@/components/HelloWorld.vue\"; import { useTestStore } from \"@/stores/test\"; test(\"pinia in component test\", () => { const wrapper = mount(HelloWorld, { global: { plugins: [createTestingPinia()], }, }); const store = useTestStore(); store.title = \"xxxxx\"; console.log(wrapper.text()) //\"hhhhh\"; });- 使用 initialState 试图覆盖原始存储的内容,但再次没有任何效果。
// test.spec.js import { mount } from \"@vue/test-utils\"; import { createTestingPinia } from \"@pinia/testing\"; import HelloWorld from \"@/components/HelloWorld.vue\"; test(\"pinia in component test\", () => { const wrapper = mount(HelloWorld, { global: { plugins: [createTestingPinia({ initialState: { title: \"xxxxx\" } })], }, }); console.log(wrapper.text()) //\"hhhhh\"; });- 修改测试代码中传递给 global.plugins 的 TestingPinia 对象,但再次没有效果。
// test.spec.js import { mount } from \"@vue/test-utils\"; import { createTestingPinia } from \"@pinia/testing\"; import HelloWorld from \"@/components/HelloWorld.vue\"; test(\"pinia in component test\", () => { const pinia = createTestingPinia(); pinia.state.value.title = \"xxxxx\"; const wrapper = mount(HelloWorld, { global: { plugins: [pinia], }, }); console.log(wrapper.text()) //\"hhhhh\"; });- 使用 global.mocks 来模拟组件中使用的状态,但这仅适用于组件中使用 setup() 传入的状态,而使用 mapState() 传入的状态无效。
// test.spec.js import { mount } from \"@vue/test-utils\"; import { createTestingPinia } from \"@pinia/testing\"; import HelloWorld from \"@/components/HelloWorld.vue\"; test(\"pinia in component test\", () => { const wrapper = mount(HelloWorld, { global: { plugins: [createTestingPinia()], mocks: { title: \"xxxxx\" }, }, }); console.log(wrapper.text()) //\"hhhhh\" });
标签: javascript vue.js jestjs vue-test-utils pinia