0
0
Vueframework~7 mins

Mocking composables and stores in Vue

Choose your learning style9 modes available
Introduction

Mocking composables and stores helps you test Vue components without relying on real data or side effects. It makes tests faster and more reliable.

When you want to test a component that uses a composable but avoid calling its real logic.
When you want to simulate different store states in a component test.
When you want to isolate component behavior from external dependencies.
When you want to control the data returned by composables or stores during tests.
When you want to avoid network calls or complex logic in unit tests.
Syntax
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.

Examples
This mocks a Pinia store composable to provide a fake user and a mocked login method.
Vue
vi.mock('@/stores/userStore', () => ({
  useUserStore: () => ({
    user: { name: 'Test User' },
    login: vi.fn()
  })
}))
This mocks a composable that returns reactive data and loading state.
Vue
import { ref } from 'vue'

vi.mock('@/composables/useFetchData', () => ({
  useFetchData: () => ({
    data: ref('mocked data'),
    loading: ref(false)
  })
}))
Sample Program

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.

Vue
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)
OutputSuccess
Important Notes

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.

Summary

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.