Given a Vue component that uses a composable returning a reactive count, and the composable is mocked to return a fixed count, what will the component render?
/* Composable: useCounter.js */ import { ref } from 'vue'; export function useCounter() { const count = ref(0); function increment() { count.value++; } return { count, increment }; } /* Component: CounterDisplay.vue */ <template> <div>{{ count }}</div> </template> <script setup> import { useCounter } from './useCounter'; const { count } = useCounter(); </script> /* Test file snippet */ vi.mock('./useCounter', () => ({ useCounter: () => ({ count: 42 }) }));
Think about what the mock returns and how the component uses it.
The mock replaces the composable's return with a fixed value. Since the component uses the mocked count directly, it renders '42'.
In a test, mocking a Pinia store's state directly causes a TypeError: Cannot read property 'value' of undefined. What is the likely cause?
import { setActivePinia, createPinia } from 'pinia'; import { useUserStore } from '@/stores/user'; setActivePinia(createPinia()); vi.mock('@/stores/user', () => ({ useUserStore: () => ({ state: { name: 'Alice' } }) })); const store = useUserStore(); console.log(store.name);
Consider how Pinia stores expose state and reactivity.
Pinia stores return reactive objects. Mocking with plain objects loses reactivity, causing errors when code expects refs or reactive proxies.
Choose the correct way to mock a composable that returns a reactive ref count initialized to 10.
/* Original composable: useCount.js */ import { ref } from 'vue'; export function useCount() { const count = ref(0); return { count }; }
Remember how the original composable returns a ref.
The original composable returns a ref. The mock must also return a ref to keep the same interface and reactivity.
Given a Pinia store with a count state and an increment action, if the store is mocked to start with count = 5, what is the value of count after calling increment() once?
/* Store definition */ import { defineStore } from 'pinia'; export const useCounterStore = defineStore('counter', { state: () => ({ count: 0 }), actions: { increment() { this.count++; } } }); /* Test mock */ vi.mock('@/stores/counter', () => ({ useCounterStore: () => ({ count: 5, increment() { this.count++; } }) })); const store = useCounterStore(); store.increment(); const result = store.count;
Check how the mocked increment method modifies the count property.
The mocked store starts with count 5. Calling increment increases count by 1, so the final value is 6.
When mocking Vue composables or Pinia stores, why must the mock preserve the original's reactive structure (e.g., refs, reactive objects) instead of returning plain values?
Think about how Vue tracks changes to update the screen.
Vue uses reactivity to detect changes and update the UI. If mocks return plain values, Vue cannot track changes, so the UI won't update as expected during tests.