Testing Vue 3 Composables with Vitest
Vue 3 composables are plain functions that use Vue's reactivity APIs — they can be tested without mounting a component. This guide shows how to test composables directly using a minimal Vue app wrapper, and how to handle reactive dependencies, async behavior, and lifecycle hooks in isolation.
Key Takeaways
Composables need an active component instance — use a wrapper app. Calling a composable outside a component context throws a warning; wrapping in withSetup or a minimal component gives it the context it needs.
ref and reactive values are testable synchronously. Read .value directly, mutate it, and assert — no mounting, no DOM.
Async composables need flushPromises() before assertions. await inside onMounted or watch is deferred; flushPromises() drains the microtask queue before you assert.
Mock external dependencies at the module level. Composables often import fetch, router, or other composables — mock those modules so the composable under test runs in isolation.
Lifecycle hooks run in the wrapper component's lifecycle. onMounted fires when the wrapper mounts; onUnmounted fires when you call wrapper.unmount().
Composables are the primary code-sharing mechanism in Vue 3. They encapsulate reactive state, computed values, watchers, and lifecycle hooks into reusable functions. Because they are plain JavaScript functions built on Vue's reactivity system, they are highly testable — often without mounting a real component.
The Challenge: Composable Context
Vue 3 composables use APIs like ref, computed, watch, and onMounted that require an active component instance. Calling a composable in a plain test file will work for ref and computed, but lifecycle hooks (onMounted, onUnmounted) will throw a warning or silently do nothing.
The solution is a lightweight wrapper that provides the component context.
The withSetup Pattern
A withSetup helper mounts a minimal component that runs your composable in setup():
import { createApp } from 'vue'
export function withSetup<T>(composable: () => T): [T, ReturnType<typeof createApp>] {
let result: T
const app = createApp({
setup() {
result = composable()
return () => null
},
})
app.mount(document.createElement('div'))
return [result!, app]
}Usage in tests:
import { withSetup } from './test-utils'
import { useCounter } from '@/composables/useCounter'
test('counter starts at 0 and increments', () => {
const [counter, app] = withSetup(() => useCounter())
expect(counter.count.value).toBe(0)
counter.increment()
expect(counter.count.value).toBe(1)
counter.increment()
expect(counter.count.value).toBe(2)
app.unmount()
})Always call app.unmount() after the test to trigger cleanup (watchers, onUnmounted hooks).
Testing Basic Reactive State
For composables without lifecycle hooks, you can often skip the wrapper entirely and call the composable directly:
import { useCounter } from '@/composables/useCounter'
// Simple composable with no lifecycle hooks
// export function useCounter(initial = 0) {
// const count = ref(initial)
// const increment = () => count.value++
// const reset = () => { count.value = 0 }
// return { count, increment, reset }
// }
test('useCounter initializes with provided value', () => {
const { count, increment, reset } = useCounter(10)
expect(count.value).toBe(10)
increment()
expect(count.value).toBe(11)
reset()
expect(count.value).toBe(0)
})When composables only use ref, reactive, and computed — no lifecycle hooks or watch — direct invocation works fine.
Testing Computed Values
Computed values update synchronously when their dependencies change:
import { useShoppingCart } from '@/composables/useShoppingCart'
test('total updates when items change', () => {
const { items, total, addItem } = useShoppingCart()
expect(total.value).toBe(0)
addItem({ id: 1, name: 'Widget', price: 15, quantity: 2 })
expect(total.value).toBe(30)
addItem({ id: 2, name: 'Gadget', price: 10, quantity: 1 })
expect(total.value).toBe(40)
})Testing Lifecycle Hooks
Lifecycle hooks fire at specific points in the component lifecycle. Use withSetup to control when they fire:
import { withSetup } from './test-utils'
import { vi } from 'vitest'
import { useEventListener } from '@/composables/useEventListener'
test('adds event listener on mount and removes on unmount', () => {
const addEventSpy = vi.spyOn(window, 'addEventListener')
const removeEventSpy = vi.spyOn(window, 'removeEventListener')
const handler = vi.fn()
const [, app] = withSetup(() => useEventListener('resize', handler))
// onMounted fires when the wrapper app mounts
expect(addEventSpy).toHaveBeenCalledWith('resize', handler)
// onUnmounted fires when we unmount the wrapper
app.unmount()
expect(removeEventSpy).toHaveBeenCalledWith('resize', handler)
})This pattern is essential for composables that register and clean up DOM event listeners, timers, or subscriptions.
Testing Async Composables
Composables that fetch data or perform async operations on mount are common. Use flushPromises() to drain the microtask queue before asserting:
import { withSetup } from './test-utils'
import { flushPromises } from '@vue/test-utils'
import { vi } from 'vitest'
import { useUserData } from '@/composables/useUserData'
import * as api from '@/api'
test('fetches user data on mount', async () => {
vi.spyOn(api, 'fetchUser').mockResolvedValue({
id: 1,
name: 'Alice',
email: 'alice@example.com',
})
const [result, app] = withSetup(() => useUserData(1))
expect(result.isLoading.value).toBe(true)
expect(result.user.value).toBeNull()
await flushPromises()
expect(result.isLoading.value).toBe(false)
expect(result.user.value?.name).toBe('Alice')
app.unmount()
})
test('sets error state when fetch fails', async () => {
vi.spyOn(api, 'fetchUser').mockRejectedValue(new Error('Not found'))
const [result, app] = withSetup(() => useUserData(99))
await flushPromises()
expect(result.user.value).toBeNull()
expect(result.error.value).toBe('Not found')
app.unmount()
})Testing Watchers
Watchers are also deferred — they run after the current microtask. Use nextTick or flushPromises before asserting on watcher effects:
import { nextTick, ref } from 'vue'
import { withSetup } from './test-utils'
import { useDebounce } from '@/composables/useDebounce'
test('debounced value updates after delay', async () => {
vi.useFakeTimers()
const source = ref('initial')
const [{ debouncedValue }, app] = withSetup(() => useDebounce(source, 300))
expect(debouncedValue.value).toBe('initial')
source.value = 'updated'
await nextTick()
// Before timer fires, debounced value is still old
expect(debouncedValue.value).toBe('initial')
vi.advanceTimersByTime(300)
await nextTick()
expect(debouncedValue.value).toBe('updated')
app.unmount()
vi.useRealTimers()
})Mocking Reactive Dependencies
When a composable depends on other composables (like useRoute, useRouter, or a custom composable), mock them at the module level:
import { vi } from 'vitest'
import { ref } from 'vue'
// Mock useRoute before importing the composable that depends on it
vi.mock('vue-router', () => ({
useRoute: () => ({
params: ref({ id: '42' }),
query: ref({ tab: 'settings' }),
}),
useRouter: () => ({
push: vi.fn(),
replace: vi.fn(),
}),
}))
import { usePageData } from '@/composables/usePageData'
test('reads route params to fetch page data', async () => {
vi.spyOn(api, 'fetchPage').mockResolvedValue({ id: 42, title: 'Settings' })
const [result, app] = withSetup(() => usePageData())
await flushPromises()
expect(api.fetchPage).toHaveBeenCalledWith('42')
expect(result.pageTitle.value).toBe('Settings')
app.unmount()
})Testing Composables with provide/inject
Some composables use provide and inject. Test the provider and consumer together using the wrapper pattern:
import { withSetup } from './test-utils'
import { defineComponent } from 'vue'
import { mount } from '@vue/test-utils'
import { useThemeProvider, useTheme } from '@/composables/useTheme'
test('theme consumer reads value from provider', () => {
const Consumer = defineComponent({
setup() {
const { theme, isDark } = useTheme()
return { theme, isDark }
},
template: '<div class="theme">{{ theme }}</div>',
})
const Provider = defineComponent({
setup() {
const { setTheme } = useThemeProvider('light')
return { setTheme }
},
components: { Consumer },
template: '<Consumer />',
})
const wrapper = mount(Provider)
expect(wrapper.find('.theme').text()).toBe('light')
})Reusable Test Helpers
As your composable test suite grows, extract common patterns into helpers:
// composable-test-helpers.ts
import { createApp } from 'vue'
import { flushPromises } from '@vue/test-utils'
export async function setupComposable<T>(composable: () => T) {
let result: T
const app = createApp({
setup() {
result = composable()
return () => null
},
})
app.mount(document.createElement('div'))
await flushPromises()
return {
result: result!,
unmount: () => app.unmount(),
}
}Using the helper:
test('useNotifications shows and auto-dismisses messages', async () => {
vi.useFakeTimers()
const { result, unmount } = await setupComposable(() => useNotifications())
result.show({ type: 'success', text: 'Saved!' })
expect(result.messages.value).toHaveLength(1)
vi.advanceTimersByTime(3000)
await nextTick()
expect(result.messages.value).toHaveLength(0)
unmount()
vi.useRealTimers()
})What Not to Test
Do not test Vue's reactivity system. If you write a test to verify that ref updates when you set .value, you are testing Vue — not your composable.
Do not assert on internal implementation. Test the public API of the composable (what it returns), not how it achieves its result internally.
Do not skip cleanup. Always call app.unmount(). Lingering watchers and timers from previous tests cause flaky, order-dependent failures.
Testing composables in isolation, with clear lifecycle control and mocked dependencies, produces a fast and reliable test suite that catches regressions without the overhead of full component rendering.