使用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"
});
最佳答案
这已使用 jest.mock()
解决。
import { mount } from "@vue/test-utils";
import { createPinia } from "pinia";
import HelloWorld from "@/components/HelloWorld.vue";
jest.mock("@/stores/test", () => {
const { defineStore } = require("pinia");
const useTestStore = defineStore("test", { state: () => ({ title: "xxxxx" }) });
return { useTestStore };
});
test("pinia in component test", () => {
const wrapper = mount(HelloWorld, {
global: { plugins: [createPinia()] },
});
expect(wrapper.text()).toBe("xxxxx");
});
关于javascript - vue3组件测试中如何修改pinia中state的值影响组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71404210/