Performance: Mocking composables and stores
This affects page load speed and interaction responsiveness by controlling how much code and state logic runs during testing or development.
import { vi } from 'vitest'; import { useUserStore } from '@/stores/user'; vi.mock('@/stores/user', () => ({ useUserStore: () => ({ user: { name: 'Test' }, fetchUser: vi.fn() }) })); export default { setup() { const userStore = useUserStore(); return { userStore }; } };
import { useUserStore } from '@/stores/user'; export default { setup() { const userStore = useUserStore(); return { userStore }; } };
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Using real composables/stores in tests | High (full reactive tree) | Multiple reflows per state change | High paint cost due to frequent updates | [X] Bad |
| Mocking composables/stores with lightweight fakes | Low (minimal reactive nodes) | Single or no reflows | Low paint cost with fewer updates | [OK] Good |
useAuth using Vitest's vi.mock()?vi.mock('./store', () => ({ useStore: () => ({ count: 5, increment: vi.fn() }) }))
const store = useStore();
store.increment();
console.log(store.count);useStore returns an object with count: 5 and increment as a mock function.count property is 5 and is not changed by calling increment() because it's a mock function without implementation.vi.mock('./useCounter', () => ({
useCounter: {
count: 0,
increment: vi.fn()
}
}))fetchData action. How do you mock the store to verify fetchData is called without running its real logic?fetchData as a mock function.vi.mock() to replace the store modulefetchData without executing its real code.vi.mock() to replace the store module with a mock where fetchData is a vi.fn() -> Option DPass the test and this pattern moves unknown