设置语法中的自定义 $reset pinia store 方法会破坏 Vitest 测试

问题描述 投票:0回答:1

我创建了一个自定义插件来从选项 API 语法中复制 $reset 方法,以用于我的 Vue 应用程序中的设置语法。

插件代码:

import cloneDeep from 'lodash.clonedeep';
import type { Store } from 'pinia';

export default function resetStore({ store }: { store: Store }) {
    const initialState = cloneDeep(store.$state);
    store.$reset = () => store.$patch(cloneDeep(initialState));
}

它是通过 main.ts 文件连接的,如下所示:

import resetStore from './plugins/resetStore';

const app = createApp(App);
app.use(createPinia().use(resetStore));

函数的使用方式如下:

const store = useStore();
store.$reset();

当我运行 Vitest 单元测试时,它们失败了,使用此函数时出现错误:

Error: 🍍: Store "clients" is built using the setup syntax and does not implement $reset().
Proxy.$reset node_modules/pinia/dist/pinia.mjs:1342:27

在这个测试文件(错误的来源)中,我像这样初始化 Pinia:

beforeEach(() => {
    setActivePinia(createPinia());
});

这是另一个商店测试,所以没有安装组件。

如何修复测试?

vue.js plugins pinia vitest
1个回答
0
投票

原来解决方案在文档中。更改测试文件中的 beforeEach 函数解决了问题。使用插件是不够的,必须创建一个应用程序实例。

const app = createApp({});
beforeEach(() => {
    const pinia = createPinia().use(resetStore);
    app.use(pinia);
    setActivePinia(pinia);
});

文档参考

© www.soinside.com 2019 - 2024. All rights reserved.