Mocking composables and stores helps you test Vue components without relying on real data or side effects. It makes tests faster and more reliable.
Mocking composables and stores in Vue
import { vi } from 'vitest' import * as composableModule from '@/composables/useExample' vi.mock('@/composables/useExample', () => ({ useExample: () => ({ data: 'mocked data', method: vi.fn() }) }))
Use vi.mock() to replace the real composable or store module with a mock version.
Return the mocked functions or data you want your component to use during tests.
vi.mock('@/stores/userStore', () => ({ useUserStore: () => ({ user: { name: 'Test User' }, login: vi.fn() }) }))
import { ref } from 'vue' vi.mock('@/composables/useFetchData', () => ({ useFetchData: () => ({ data: ref('mocked data'), loading: ref(false) }) }))
This test mocks the useCounter composable to return a fixed count and a mocked increment function. It mounts MyComponent which uses this composable. Then it logs the rendered text and checks how many times increment was called.
import { mount } from '@vue/test-utils' import { vi } from 'vitest' import { ref } from 'vue' import MyComponent from '@/components/MyComponent.vue' // Mock the composable vi.mock('@/composables/useCounter', () => { const count = ref(10) const increment = vi.fn() return { useCounter: () => ({ count, increment }) } }) import { useCounter } from '@/composables/useCounter' // Test const wrapper = mount(MyComponent) console.log(wrapper.text()) // Call increment method useCounter().increment() console.log(useCounter().increment.mock.calls.length)
Always import the mocked composable after calling vi.mock() to ensure the mock is applied.
Use vi.fn() to create mock functions you can track in tests.
Mocking helps keep tests fast and focused on the component, not external logic.
Mock composables and stores to isolate component tests from real logic.
Use vi.mock() to replace modules with fake versions.
Mock functions let you check calls and control behavior in tests.