Vue.js course ยท Module 9: Composables & VueUse

Testing Composables

8 min read ยท
In this lesson6

Every critical NOVA LAB station system must pass rigorous testing before deployment. The same goes for composables - we need to be sure they work correctly in every scenario. Think about scale: one composable works in ten components, so one bug in it breaks ten screens at once. A test written at the composable level catches such a bug in a single run, before the crew ever sees it.

Setting Up the Test Environment

To test composables we use Vitest, the testing tool from the Vite ecosystem, and helpers such as flushPromises come from the @vue/test-utils package. The Vue documentation distinguishes two cases. A composable that uses only ref, computed and watch can simply be called in a test. A composable with lifecycle hooks or with inject needs a host component, and that is provided by a helper function that runs it inside a test component:

// test-utils.ts
import { createApp, defineComponent } from 'vue'

// Helper: run composable in an isolated component
export function withSetup(composable) {
  let result

  const TestComponent = defineComponent({
    setup() {
      result = composable()
      return () => {} // empty render
    }
  })

  const app = createApp(TestComponent)
  app.mount(document.createElement('div'))

  return { result, app }
}

The test component calls the composable in setup, renders an empty function and is mounted into an element that is not on any page. document exists in the test thanks to DOM simulation, so in the Vitest configuration set test.environment to 'happy-dom' or 'jsdom'. The returned app will come in handy for unmounting.

Testing a Simple Composable

Let's start with a counter. In the test file you import the Vitest functions, the composable itself and the helper:

import { describe, it, expect } from 'vitest'
import { ref } from 'vue'
import { withSetup } from './test-utils'

// Composable to test
function useCounter(initial = 0) {
  const count = ref(initial)
  const increment = () => count.value++
  const decrement = () => count.value--
  const reset = () => { count.value = initial }
  return { count, increment, decrement, reset }
}

describe groups the tests of one composable, each it is a separate scenario, and expect(...).toBe(...) compares the result with the expected value:

describe('useCounter', () => {
  it('starts with initial value', () => {
    const { result } = withSetup(() => useCounter(10))
    expect(result.count.value).toBe(10)
  })

  it('defaults to 0', () => {
    const { result } = withSetup(() => useCounter())
    expect(result.count.value).toBe(0)
  })

  it('increments value', () => {
    const { result } = withSetup(() => useCounter())
    result.increment()
    expect(result.count.value).toBe(1)
    result.increment()
    expect(result.count.value).toBe(2)
  })

  it('decrements value', () => {
    const { result } = withSetup(() => useCounter(5))
    result.decrement()
    expect(result.count.value).toBe(4)
  })

  it('resets to initial value', () => {
    const { result } = withSetup(() => useCounter(10))
    result.increment()
    result.increment()
    result.reset()
    expect(result.count.value).toBe(10)
  })
})

Every test creates a fresh counter, so the result of one does not affect another. This composable uses only ref, so it would also work without the helper; we use it for consistency with the next examples.

Mocking Reactive Dependencies

When a composable depends on external data sources, we mock them. It's easiest when the dependency comes in as a parameter - here the fetchFn function:

import { describe, it, expect, vi } from 'vitest'
import { ref, nextTick } from 'vue'
import { withSetup } from './test-utils'

// Composable with fetch dependency
function useSensorData(fetchFn) {
  const data = ref(null)
  const error = ref(null)
  const loading = ref(false)

  async function load(sensorId) {
    loading.value = true
    error.value = null
    try {
      data.value = await fetchFn(sensorId)
    } catch (e) {
      error.value = e.message
    } finally {
      loading.value = false
    }
  }

  return { data, error, loading, load }
}

vi.fn() creates a fake function that remembers its calls. mockResolvedValue makes it return a promise fulfilled with the given object, and mockRejectedValue - one rejected with an error:

describe('useSensorData', () => {
  it('loads data from server', async () => {
    // Mock fetch function
    const mockFetch = vi.fn().mockResolvedValue({
      id: 'T-01',
      temperature: 22,
      status: 'active'
    })

    const { result } = withSetup(() => useSensorData(mockFetch))

    expect(result.loading.value).toBe(false)

    await result.load('T-01')

    expect(mockFetch).toHaveBeenCalledWith('T-01')
    expect(result.data.value).toEqual({
      id: 'T-01',
      temperature: 22,
      status: 'active'
    })
    expect(result.loading.value).toBe(false)
  })

  it('handles errors', async () => {
    const mockFetch = vi.fn().mockRejectedValue(
      new Error('Server unavailable')
    )

    const { result } = withSetup(() => useSensorData(mockFetch))

    await result.load('T-01')

    expect(result.error.value).toBe('Server unavailable')
    expect(result.data.value).toBeNull()
  })
})

toHaveBeenCalledWith checks the call arguments, and toEqual compares objects field by field, because toBe would require the same reference. No test touched a real server.

Testing Composables with watch

Here lies an important difference. computed is recalculated synchronously at the moment it is read, while Vue defers the watch callback until the next tick, that is until the current synchronous code has finished. That is why we add a search counter driven by watch to the filter:

import { describe, it, expect } from 'vitest'
import { ref, watch, nextTick, computed } from 'vue'
import { withSetup } from './test-utils'

function useSearchFilter(items) {
  const query = ref('')
  const searchCount = ref(0)

  const filtered = computed(() => {
    if (!query.value) return items.value
    return items.value.filter(item =>
      item.name.toLowerCase().includes(query.value.toLowerCase())
    )
  })

  // watch counts query changes - its callback waits for the next tick
  watch(query, () => {
    searchCount.value++
  })

  return { query, filtered, searchCount }
}

Both strings are compared in lowercase, so letter case doesn't matter - you will write the test for the query 'TEMP' in the practice task. The third test below shows what nextTick is for:

describe('useSearchFilter', () => {
  it('filters items by query', async () => {
    const items = ref([
      { name: 'Temperature sensor' },
      { name: 'Pressure sensor' },
      { name: 'Radiation sensor' }
    ])

    const { result } = withSetup(() => useSearchFilter(items))

    // Initially all items
    expect(result.filtered.value).toHaveLength(3)

    // Filtering
    result.query.value = 'temp'
    await nextTick()

    expect(result.filtered.value).toHaveLength(1)
    expect(result.filtered.value[0].name).toBe('Temperature sensor')
  })

  it('returns all for empty query', async () => {
    const items = ref([{ name: 'A' }, { name: 'B' }])
    const { result } = withSetup(() => useSearchFilter(items))

    result.query.value = 'A'
    await nextTick()
    expect(result.filtered.value).toHaveLength(1)

    result.query.value = ''
    await nextTick()
    expect(result.filtered.value).toHaveLength(2)
  })

  it('counts query changes only after nextTick', async () => {
    const items = ref([{ name: 'A' }])
    const { result } = withSetup(() => useSearchFilter(items))

    result.query.value = 'A'
    expect(result.searchCount.value).toBe(0) // watch has not run yet

    await nextTick()
    expect(result.searchCount.value).toBe(1)
  })
})

In the first two tests filtered would give the correct result even without await nextTick(), because it is a computed. In the third one, without waiting the counter stays at zero. flushPromises from @vue/test-utils goes one step further: it waits until all pending promises have resolved.

Testing Asynchronous Composables

We test a composable that polls the server every few seconds with Vitest's fake timers, so the test doesn't actually wait. This is the code under test:

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { ref, onMounted, onUnmounted } from 'vue'
import { withSetup } from './test-utils'

function usePolling(fetchFn, interval = 5000) {
  const data = ref(null)
  const isPolling = ref(false)
  let timerId = null

  function startPolling() {
    isPolling.value = true
    timerId = setInterval(async () => {
      data.value = await fetchFn()
    }, interval)
  }

  function stopPolling() {
    isPolling.value = false
    if (timerId) {
      clearInterval(timerId)
      timerId = null
    }
  }

  onUnmounted(stopPolling)

  return { data, isPolling, startPolling, stopPolling }
}

vi.useFakeTimers() replaces setInterval with a clock that we move forward by hand, and vi.useRealTimers() restores the real one. advanceTimersByTimeAsync moves time forward and also waits for the promises returned by the timers:

describe('usePolling', () => {
  beforeEach(() => {
    vi.useFakeTimers()
  })

  afterEach(() => {
    vi.useRealTimers()
  })

  it('polls the server at specified intervals', async () => {
    let callCount = 0
    const mockFetch = vi.fn().mockImplementation(() => {
      callCount++
      return Promise.resolve({ reading: callCount * 10 })
    })

    const { result } = withSetup(() => usePolling(mockFetch, 1000))

    result.startPolling()
    expect(result.isPolling.value).toBe(true)

    // Simulate time passing (the Async version also waits for promises)
    await vi.advanceTimersByTimeAsync(3000)

    expect(mockFetch).toHaveBeenCalledTimes(3)
    expect(result.data.value).toEqual({ reading: 30 })

    result.stopPolling()
    expect(result.isPolling.value).toBe(false)
  })

After three simulated seconds the server has answered three times, and data holds the last reading. The synchronous advanceTimersByTime would also call mockFetch three times, but data would stay empty. Finally a cleanup test, in which app.unmount() triggers onUnmounted:

  it('cleans up the timer after unmount', async () => {
    const mockFetch = vi.fn().mockResolvedValue({ reading: 1 })
    const { result, app } = withSetup(() => usePolling(mockFetch, 1000))

    result.startPolling()
    app.unmount() // triggers onUnmounted -> stopPolling

    await vi.advanceTimersByTimeAsync(5000)
    expect(mockFetch).not.toHaveBeenCalled()
    expect(result.isPolling.value).toBe(false)
  })
})

Five seconds after unmounting, nobody polled the server - the timer really is gone.

Testing Best Practices

  1. Isolation - each test should be independent
  2. Mocking - always mock external dependencies
  3. Asynchrony - use nextTick for watchers and DOM updates, and flushPromises for pending promises
  4. Cleanup - check that the composable cleans up resources properly, for example with app.unmount()
  5. Edge cases - test empty data, errors, boundary values

My advice: design composables so that their dependencies come in as parameters, like fetchFn. A mock is then a single line, and the test doesn't need to replace the global fetch. You will extend your tests to components at the Launch Platform. In the editor below, a miniature test runner works in the browser: it checks useCounter, useSearchFilter and useAsyncData, and shows the results on the panel.

Remember: a test is a module's pressure check before launch - better to find the leak in the lab than in orbit.

Code for this lesson: App.vue
<script setup>
import { ref, computed, watch, nextTick } from 'vue'

// ===== TESTING COMPOSABLES DEMO =====

// Composable: useCounter (under test)
function useCounter(initial = 0) {
  const count = ref(initial)
  const doubled = computed(() => count.value * 2)
  const increment = () => count.value++
  const decrement = () => count.value--
  const reset = () => { count.value = initial }
  return { count, doubled, increment, decrement, reset }
}

// Composable: useSearchFilter (under test)
function useSearchFilter(items) {
  const query = ref('')
  const filtered = computed(() => {
    if (!query.value) return items.value
    return items.value.filter(item =>
      item.name.toLowerCase().includes(query.value.toLowerCase())
    )
  })
  return { query, filtered }
}

// Composable: useAsyncData (under test)
function useAsyncData(fetchFn) {
  const data = ref(null)
  const error = ref(null)
  const loading = ref(false)

  async function load(...args) {
    loading.value = true
    error.value = null
    try {
      data.value = await fetchFn(...args)
    } catch (e) {
      error.value = e.message
    } finally {
      loading.value = false
    }
  }

  return { data, error, loading, load }
}

// === Test Runner ===
const testResults = ref([])
const totalPassed = computed(() => testResults.value.filter(t => t.passed).length)
const totalFailed = computed(() => testResults.value.filter(t => !t.passed).length)

function assert(condition, testName) {
  testResults.value.push({
    name: testName,
    passed: condition,
    timestamp: new Date().toLocaleTimeString()
  })
}

async function runAllTests() {
  testResults.value = []

  // Test useCounter
  const counter = useCounter(10)
  assert(counter.count.value === 10, 'useCounter: starts with initial value')
  counter.increment()
  assert(counter.count.value === 11, 'useCounter: increment works')
  assert(counter.doubled.value === 22, 'useCounter: doubled computed works')
  counter.decrement()
  counter.decrement()
  assert(counter.count.value === 9, 'useCounter: decrement works')
  counter.reset()
  assert(counter.count.value === 10, 'useCounter: reset returns to initial')

  const defaultCounter = useCounter()
  assert(defaultCounter.count.value === 0, 'useCounter: default initial is 0')

  // Test useSearchFilter
  const items = ref([
    { name: 'Temperature Sensor' },
    { name: 'Pressure Sensor' },
    { name: 'Radiation Detector' }
  ])
  const filter = useSearchFilter(items)
  assert(filter.filtered.value.length === 3, 'useSearchFilter: shows all initially')

  filter.query.value = 'sensor'
  await nextTick()
  assert(filter.filtered.value.length === 2, 'useSearchFilter: filters by query')

  filter.query.value = 'radiation'
  await nextTick()
  assert(filter.filtered.value.length === 1, 'useSearchFilter: exact match')
  assert(filter.filtered.value[0].name === 'Radiation Detector', 'useSearchFilter: correct item')

  filter.query.value = ''
  await nextTick()
  assert(filter.filtered.value.length === 3, 'useSearchFilter: empty query shows all')

  // Test useAsyncData
  const successData = useAsyncData(async () => ({ temp: 22, status: 'OK' }))
  assert(successData.loading.value === false, 'useAsyncData: not loading initially')
  assert(successData.data.value === null, 'useAsyncData: no data initially')

  await successData.load()
  assert(successData.data.value !== null, 'useAsyncData: has data after load')
  assert(successData.data.value.temp === 22, 'useAsyncData: correct data')
  assert(successData.error.value === null, 'useAsyncData: no error on success')

  const failData = useAsyncData(async () => { throw new Error('Connection lost') })
  await failData.load()
  assert(failData.error.value === 'Connection lost', 'useAsyncData: captures error')
  assert(failData.data.value === null, 'useAsyncData: no data on error')
}
</script>

<template>
  <div class="test-lab">
    <h1>Testing Composables - NOVA LAB</h1>

    <div class="controls">
      <button @click="runAllTests" class="run-btn">Run All Tests</button>
    </div>

    <div v-if="testResults.length" class="summary">
      <span class="passed">Passed: {{ totalPassed }}</span>
      <span class="failed">Failed: {{ totalFailed }}</span>
      <span class="total">Total: {{ testResults.length }}</span>
    </div>

    <div class="results">
      <div v-for="(test, i) in testResults" :key="i"
        class="test-result" :class="{ pass: test.passed, fail: !test.passed }">
        <span class="icon">{{ test.passed ? 'PASS' : 'FAIL' }}</span>
        <span class="test-name">{{ test.name }}</span>
      </div>
    </div>

    <div v-if="!testResults.length" class="empty">
      Click "Run All Tests" to execute test suite
    </div>
  </div>
</template>

<style scoped>
.test-lab { background: #0a0e27; color: #e0e0ff; padding: 1.5rem; min-height: 100vh; font-family: 'Courier New', monospace; }
h1 { color: #00ff88; text-align: center; margin-bottom: 2rem; }
.controls { text-align: center; margin: 1rem 0; }
.run-btn { background: #00ff88; color: #0a0e27; border: none; padding: 0.8rem 2rem; border-radius: 6px; font-size: 1.1rem; font-weight: bold; cursor: pointer; font-family: inherit; }
.run-btn:hover { background: #00b4d8; color: #fff; }
.summary { display: flex; justify-content: center; gap: 2rem; padding: 1rem; background: rgba(0,0,0,0.3); border-radius: 8px; margin: 1rem 0; font-size: 1.1rem; }
.passed { color: #00ff88; }
.failed { color: #ff0055; }
.total { color: #00b4d8; }
.results { margin: 1rem 0; }
.test-result { display: flex; align-items: center; gap: 0.8rem; padding: 0.5rem 0.8rem; margin: 0.2rem 0; border-radius: 4px; font-size: 0.9rem; }
.test-result.pass { background: rgba(0,255,136,0.08); border-left: 3px solid #00ff88; }
.test-result.fail { background: rgba(255,0,85,0.08); border-left: 3px solid #ff0055; }
.icon { font-weight: bold; font-size: 0.8rem; padding: 0.15rem 0.4rem; border-radius: 3px; }
.pass .icon { background: #00ff88; color: #0a0e27; }
.fail .icon { background: #ff0055; color: #fff; }
.test-name { color: #ccc; }
.empty { text-align: center; color: #666; padding: 3rem; font-style: italic; }
</style>

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Why do we need the withSetup helper for testing composables?

  2. 2. How do we mock external dependencies in composable tests?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Create a test component with useSensorData. Mock fetchFn using vi.fn(). Check loading, data, error after calling load().

  • Vertical ordering

    Arrange the unit test steps for a composable from preparation to assertion:

  • Click in order

    Arrange a correct assertion checking a ref value:

  • Code editor

    Test useSearchFilter: filtering by query, empty query returns all items, case-insensitive matching.

  • Horizontal ordering

    Arrange the creation of a mock fetch function:

  1. QuestionwithSetup Helper in Tests
  2. QuestionMocking in Composable Tests
  3. Coding taskPractice: Test a Composable with a Mock
  4. Put in orderSteps for Testing a Composable
  5. QuestionnextTick in Tests
  6. Click in orderAssertion in a Composable Test
  7. Coding taskPractice: Test useSearchFilter
  8. Put in orderMocking a Function in Vitest

Useful articles