DEV Community

Cover image for How to Test Vue Composables
Alexander Opalic
Alexander Opalic

Posted on

How to Test Vue Composables


Hello everyone, in this blog post, I want to help you gain a better understanding of how to test a composable in Vue. Nowadays, much of our business logic or UI logic is often encapsulated in composables, which is why I think it's important to understand how to test them.


Before diving into the main topic, it's important to understand some basic concepts regarding testing. This foundational knowledge will help clarify where testing Vue composables fits into the broader landscape of software testing.


Composables in Vue are reusable composition functions that encapsulate and manage reactive state and logic. They allow for a flexible way to organize and reuse code across components, enhancing modularity and maintainability.

Testing Pyramid

Image description
The Testing Pyramid is a conceptual metaphor that illustrates the ideal balance of different types of testing. It recommends a large base of unit tests, supplemented by a smaller set of integration tests, and capped with an even smaller set of end-to-end tests. This structure ensures efficient and effective test coverage.

Unit Testing and How Testing a Composable Would Be a Unit Test

Unit testing refers to the practice of testing individual units of code in isolation. In the context of Vue, testing a composable is a form of unit testing. It involves rigorously verifying the functionality of these isolated, reusable code blocks, ensuring they function correctly without external dependencies.

Testing Composables

Composables in Vue are essentially functions, leveraging Vue's reactivity system. Given this unique nature, we can categorize composables into different types. On one hand, there are Independent Composables, which can be tested directly due to their standalone nature. On the other hand, we have Dependent Composables, which only function correctly when integrated within a component. In the sections that follow, I'll delve into these distinct types, provide examples for each, and guide you through effective testing strategies for both.

Independent Composables

Image description
An Independent Composable exclusively uses Vue's Reactivity APIs. These composables operate independently from Vue component instances, making them straightforward to test.

Example & Testing Strategy:

Here is an example of an independent composable that calculates the sum of two reactive values:

useSum(a: Ref<number>, b: Ref<number>): ComputedRef<number> {
  return computed(() => a.value + b.value)
Enter fullscreen mode Exit fullscreen mode

To test this composable, you would directly invoke it and assert its returned state:

Test with Vitest:

describe('useSum', () => {
  it('correctly computes the sum of two numbers', () => {
    const num1 = ref(2);
    const num2 = ref(3);
    const sum = useSum(num1, num2);

Enter fullscreen mode Exit fullscreen mode

This test directly checks the functionality of useSum by passing reactive references and asserting the computed result.

Dependent Composables

Image description
Dependent Composables are distinguished by their reliance on Vue's component instance. They often leverage features like lifecycle hooks or context for their operation. These composables are an integral part of a component and necessitate a distinct approach for testing, as opposed to Independent Composables.

Example & Usage:

An exemplary Dependent Composable is useLocalStorage. This composable facilitates interaction with the browser's localStorage and harnesses the onMounted lifecycle hook for initialization:

function useLocalStorage<T>(key: string, initialValue: T) {
  const value = ref(initialValue);

  function loadFromLocalStorage() {
    const storedValue = localStorage.getItem(key);
    if (storedValue !== null) {
      value.value = JSON.parse(storedValue);


  watch(value, (newValue) => {
    localStorage.setItem(key, JSON.stringify(newValue));

  return { value };

export default useLocalStorage;
Enter fullscreen mode Exit fullscreen mode

This composable can be utilised within a component, for instance, to create a persistent counter:

Image description

<script setup lang="ts">
import useLocalStorage from './../composables/useLocalStorage'

const { value: count } = useLocalStorage('counter', 0)

function increment() {

    <h1>Counter: {{ count }}</h1>
    <button @click="increment">Increment</button>
Enter fullscreen mode Exit fullscreen mode

The primary benefit here is the seamless synchronization of the reactive count property with localStorage, ensuring persistence across sessions.

Testing Strategy:

To effectively test useLocalStorage, especially considering the onMounted lifecycle, we initially face a challenge. Let's start with a basic test setup:

describe('useLocalStorage', () => {
  it('should load the initialValue', () => {
    const { value } = useLocalStorage('testKey', 'initValue');

  it('should load from localStorage', async () => {
    localStorage.setItem('testKey', JSON.stringify('fromStorage'));
    const { value } = useLocalStorage('testKey', 'initialValue');
Enter fullscreen mode Exit fullscreen mode

Here, the first test will pass, asserting that the composable initialises with the given initialValue. However, the second test, which expects the composable to load a pre-existing value from localStorage, fails. The challenge arises because the onMounted lifecycle hook is not triggered during testing. To address this, we need to refactor our composable or our test setup to simulate the component mounting process.

Enhancing Testing with the withSetup Helper Function

Image description

To facilitate easier testing of composables that rely on Vue's lifecycle hooks, we've developed a higher-order function named withSetup. This utility allows us to create a Vue component context programmatically, focusing primarily on the setup lifecycle function where composables are typically used.

Introduction to withSetup:

withSetup is designed to simulate a Vue component's setup function, enabling us to test composables in an environment that closely mimics their real-world use. The function accepts a composable and returns both the composable's result and a Vue app instance. This setup allows for comprehensive testing, including lifecycle and reactivity features.

import type { App } from 'vue';
import { createApp } from 'vue';

export function withSetup<T>(composable: () => T): [T, App] {
  let result: T;
  const app = createApp({
    setup() {
      result = composable();
      return () => {};
  return [result, app];
Enter fullscreen mode Exit fullscreen mode

In this implementation, withSetup mounts a minimal Vue app and executes the provided composable function during the setup phase. This approach allows us to capture and return the composable's output alongside the app instance for further testing.

Utilizing withSetup in Tests:

With withSetup, we can enhance our testing strategy for composables like useLocalStorage, ensuring they behave as expected even when they depend on lifecycle hooks:

it('should load the value from localStorage if it was set before', async () => {
  localStorage.setItem('testKey', JSON.stringify('valueFromLocalStorage'));
  const [result] = withSetup(() => useLocalStorage('testKey', 'testValue'));
Enter fullscreen mode Exit fullscreen mode

This test demonstrates how withSetup enables the composable to execute as if it were part of a regular Vue component, ensuring the onMounted lifecycle hook is triggered as expected. Additionally, the robust TypeScript support enhances the development experience by providing clear type inference and error checking.


Image description

In our exploration of testing Vue composables, we uncovered two distinct categories: Independent Composables and Dependent Composables. Independent Composables stand alone and can be tested akin to regular functions, showcasing straightforward testing procedures. Meanwhile, Dependent Composables, intricately tied to Vue's component system and lifecycle hooks, require a more nuanced approach. For these, we learned the effectiveness of utilizing a helper function, such as withSetup, to simulate a component context, enabling comprehensive testing.

I hope this blog post has been insightful and useful in enhancing your understanding of testing Vue composables. I'm also keen to learn about your experiences and methods in testing composables within your projects. Your insights and approaches could provide valuable perspectives and contribute to the broader Vue community's knowledge.

Top comments (2)

andrzej_kowal profile image
Andrzej Kowal

Thanks for the article, was useful. Will save for later, when I will have time to touch Vue by itself.

alexanderop profile image
Alexander Opalic

Ty good to hear