QA
Intermediate LevelVue JS

How do you unit test Vue components with Pinia stores using @pinia/testing?

❓ Interview Prompt: Explain testing components that depend on Pinia stores, createTestingPinia(), mocking actions, and stubbing state.

Unit testing components that rely on global Pinia stores requires providing a mock testing Pinia instance to isolate tests.

Using '@pinia/testing':

Pass 'createTestingPinia()' to Vue Test Utils mounting options:

•
Automatically stubs all store actions to prevent real network/API calls during tests.
•
Allows pre-populating mock store state and asserting whether specific store actions were called during component interactions.

Code Implementation Example

javascript
import { mount } from '@vue/test-utils';
import { createTestingPinia } from '@pinia/testing';
import UserProfile from '@/components/UserProfile.vue';
import { useUserStore } from '@/stores/userStore';

test('renders user name from Pinia store', () => {
  const wrapper = mount(UserProfile, {
    global: {
      plugins: [createTestingPinia({
        initialState: { user: { name: 'Alice' } }
      })]
    }
  });

  expect(wrapper.text()).toContain('Alice');
});
💡Unit testing a Vue component with pre-populated Pinia testing state.
🎯 Interview Key Takeaway

Use createTestingPinia() in component unit tests to stub store actions and pre-populate mock initial state.

#Pinia#Testing#Vue Test Utils#Intermediate
Back to all Vue JS Questions→

More Vue JS Interview Questions

Beginner LevelVue JS

What is the difference between Options API and Composition API in Vue 3?

Beginner LevelVue JS

What is the difference between ref() and reactive() in Vue 3?

Beginner LevelVue JS

What is the difference between computed properties, methods, and watch/watchEffect?