I'm trying to test a component that uses a Pinia store, even following the documentation correctly, I'm getting this error:
"getActivePinia()" was called but there was no active Pinia. Did you forget to install pinia?
I've also tried to call setActivePinia(createPinia())
in beforeEach, but without success.
This is my code
import { describe, expect, it, vi } from 'vitest';
import { createTestingPinia } from '@pinia/testing';
import { mount } from '@vue/test-utils';
import MyComponent from './MyComponent.vue';
describe('MyComponent', () => {
it('should', async () => {
const wrapper = mount(MainFilter, {
global: {
plugins: [
createTestingPinia({
createSpy: vi.fn
})
]
}
});
expect(wrapper.find('div')).toBe(true);
});
});
Component:
import { defineComponent } from 'vue';
import { clientsStore } from '@/stores/clients';
const store = clientsStore();
export default defineComponent({
name: 'MyComponent',
data() {
return {
form: {
id: ''
}
};
},
methods: {
onSubmit() {
store.updateMyStore(this.form);
}
}
});
The problem is that Pinia store is accessed too early, this incidentally isn't a problem in the application due to an order in which the modules are imported.
Pinia uses store composables instead of store instances to avoid the early instantiation and provide an option to provide custom Pinia instance. Store composable is supposed to be called directly in place where it's used. In case of options API it can be exposed on the instance in lifecycle hook, e.g. data
:
data() {
return {
store: useClientsStore()
form: {
id: ''
}
};
}