Search code examples
vue.jspluginspiniavitest

Custom $reset pinia store method in setup syntax breaks Vitest tests


I've created a custom plugin to replicate $reset method from Options API syntax for setup syntax in my Vue app.

The code of the plugin:

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));
}

It's connected via main.ts file like so:

import resetStore from './plugins/resetStore';

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

And the function is used like that:

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

When I run my Vitest unit tests, they fall, where this function is used with the error:

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

In this test file (where the error is from), I initialize Pinia like that:

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

It's another store tests, so a component is not mounted.

How can I fix the tests?


Solution

  • Turned out the solution is in the docs. Changing my beforeEach function in the test file solved the problem. Using a plugin is not enough, an app instance has to be created.

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

    Doc reference