Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 87 ยท Testing and Debugging

Testing Composables and Stores

Test composables with and without a host component, mock fetch, keep stores isolated between tests and use the Pinia testing helpers, with runnable examples.

Not all of your logic lives in components. A well-structured Vue app moves rules into composables and stores, so components stay thin. That is great for testing: logic without a template can be tested without mounting anything, which makes tests faster and sharper. There are two catches. Some composables need a component around them (lifecycle hooks, inject), and anything that touches the network or shared state needs care so tests do not affect each other.

In this lesson you will test a plain composable, build a withSetup helper for the ones that need a host, mock fetch for async composables, and keep store state isolated. The runnable examples use hand-written helpers, and the Pinia parts are read-only, because Pinia and Vitest are not available in the browser sandbox.

flowchart TD
    Q["Composable to test"] --> A{"Uses lifecycle hooks,<br/>provide / inject or watchers<br/>tied to a component?"}
    A -- "No: only ref, computed, functions" --> B["Call it directly<br/>in the test"]
    A -- "Yes" --> C["Run it inside a tiny host component<br/>with a withSetup helper"]
    C --> D["Unmount the host to test cleanup"]

Pure reactivity needs no host; hooks and injections need a component instance to attach to.

Composables that only use reactivity

The simplest case needs no Vue test tool at all. A composable that only uses ref and computed is just a function that returns reactive values, so call it and read the result:

JavaScript
// useCounter.js
import { ref, computed } from "vue";

export function useCounter(start = 0) {
  const count = ref(start);
  const isEven = computed(() => count.value % 2 === 0);
  const increment = () => count.value++;
  return { count, isEven, increment };
}
JavaScript
// useCounter.spec.js (Vitest, read-only)
import { describe, it, expect } from "vitest";
import { useCounter } from "./useCounter";

describe("useCounter", () => {
  it("starts at the given value", () => {
    const { count } = useCounter(5);
    expect(count.value).toBe(5);
  });

  it("derives isEven", () => {
    const { isEven, increment } = useCounter(1);
    expect(isEven.value).toBe(false);
    increment();
    expect(isEven.value).toBe(true);
  });
});

Notice that no await is needed: computed re-evaluates the moment you read it. You only need await nextTick() when you are checking something Vue schedules for later, such as DOM updates or watch callbacks with the default flush timing.

The withSetup helper

Many composables use onMounted, onUnmounted, provide/inject, or create watchers that should stop when a component dies. Those APIs attach to the current component instance. Call them in a bare test function and Vue has no instance to attach to: lifecycle hooks are ignored with a warning and inject finds nothing.

The standard fix is a few lines: mount a throwaway component whose setup() runs your composable and hands the result back.

JavaScript
import { createApp } from "vue";

function withSetup(composable) {
  let result;
  const app = createApp({
    setup() {
      result = composable();
      return () => null; // renders nothing
    },
  });
  app.mount(document.createElement("div"));
  return [result, app];
}

It returns the composable's result and the app, so a test can call app.unmount() to trigger onUnmounted and check cleanup. If the composable needs inject, add app.provide(key, value) before mounting (or take a provide option in the helper).

The next example tests a useKeyPressCount composable that listens for key presses on window. It checks counting, cleanup after unmount, and what happens when you call a lifecycle hook with no host.

Testing a composable with withSetup

The last test shows why the helper exists. Without an instance, onMounted never fires, so the listener is never attached and the composable silently does nothing (the development build also prints a console warning). If a composable test mysteriously sees no effect, check whether it needs a host.

Mocking fetch

A test must never hit the real network: it would be slow, flaky and dependent on a server being up. Replace fetch with a fake you control, and let it return exactly the responses you want to test, including failures.

Two common ways:

  1. Replace the global. In Vitest: vi.stubGlobal("fetch", vi.fn(...)), or vi.spyOn(globalThis, "fetch"). Restore it after each test with vi.unstubAllGlobals().
  2. Pass the function in. useUser(id, { fetcher = fetch } = {}) makes the dependency visible, and the test just passes a fake. This needs no mocking library at all.

The composable below fetches a user and refetches when the id ref changes. The test fakes fetch with a small function that records the URLs it was called with and answers from a table.

Mocking fetch for an async composable

Real fetch returns a Response; the fake returns only what the composable touches (ok, status, json). Keep fakes this small so the test stays readable, but add a test for each path the code can take: success, HTTP error, network failure and a changed input.

One more thing the test above does not cover is the race condition where an older request finishes after a newer one. If your composable guards against it, write a test with two deferred promises that resolve in the wrong order.

Time-dependent composables

Debounce, throttle and polling composables depend on timers. Real timers make tests slow and flaky, so use fake timers, which let the test move the clock by hand (read-only, Vitest):

JavaScript
import { vi, it, expect, beforeEach, afterEach } from "vitest";
import { ref, nextTick } from "vue";
import { useDebounce } from "./useDebounce";

beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());

it("updates the debounced value after the delay", async () => {
  const source = ref("a");
  const debounced = useDebounce(source, 300);

  source.value = "b";
  await nextTick();
  expect(debounced.value).toBe("a");   // not yet

  vi.advanceTimersByTime(300);
  expect(debounced.value).toBe("b");
});

Testing stores

A store is shared, long-lived state, and that is the danger: if tests share one store instance, the first test's changes leak into the second, and the suite passes or fails depending on the order. The fix is to give every test a fresh store. With a store written as a factory function, that is trivial:

Isolating store state between tests

The second test fails on purpose to demonstrate a leak: the first test left tea in the shared cart. The three factory-based tests pass in any order.

Testing Pinia stores

Pinia solves the isolation problem for you: stores belong to a Pinia instance, and you create a new one before each test. The read-only code below is the idiomatic Vitest setup.

JavaScript
// stores/cart.js
import { defineStore } from "pinia";
import { ref, computed } from "vue";

export const useCartStore = defineStore("cart", () => {
  const lines = ref([]);
  const total = computed(() => lines.value.reduce((sum, l) => sum + l.price * l.qty, 0));

  function add(product) {
    const line = lines.value.find((l) => l.id === product.id);
    if (line) line.qty++;
    else lines.value.push({ ...product, qty: 1 });
  }

  return { lines, total, add };
});
JavaScript
// stores/cart.spec.js
import { beforeEach, describe, it, expect } from "vitest";
import { setActivePinia, createPinia } from "pinia";
import { useCartStore } from "./cart";

describe("cart store", () => {
  beforeEach(() => {
    setActivePinia(createPinia()); // fresh Pinia, fresh stores
  });

  it("adds products and computes the total", () => {
    const cart = useCartStore();
    cart.add({ id: "tea", price: 4 });
    cart.add({ id: "tea", price: 4 });
    expect(cart.total).toBe(8);
  });
});

Test the store directly for its own logic. When you test a component that uses a store, you usually do not want the store's real logic running (or its real network calls). The official testing package @pinia/testing gives you createTestingPinia, which replaces every action with a spy and lets you set the initial state:

JavaScript
import { mount } from "@vue/test-utils";
import { createTestingPinia } from "@pinia/testing";
import { vi, it, expect } from "vitest";
import CartButton from "./CartButton.vue";
import { useCartStore } from "../stores/cart";

it("calls the add action when clicked", async () => {
  const wrapper = mount(CartButton, {
    props: { product: { id: "tea", price: 4 } },
    global: {
      plugins: [
        createTestingPinia({
          createSpy: vi.fn,
          initialState: { cart: { lines: [] } },
        }),
      ],
    },
  });
  const cart = useCartStore();

  await wrapper.get("button").trigger("click");

  expect(cart.add).toHaveBeenCalledWith({ id: "tea", price: 4 });
});

This splits responsibilities cleanly: store tests check that the logic is right; component tests check that the component calls the store correctly and renders what the store says. Neither re-tests the other.

A short checklist

  • Call pure composables directly; use withSetup when they need hooks or inject.
  • Unmount the host to test cleanup (listeners, timers, subscriptions).
  • Never use the real network; fake fetch or inject the fetcher, and test success, failure and changed input.
  • Use fake timers for debounce, throttle and polling.
  • Give each test fresh store state: a factory function, or a new Pinia in beforeEach.
  • Test logic where it lives, and keep component tests about the component.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does a composable that calls onMounted need a helper like withSetup in a test?

    Hooks attach to the current component instance. In a bare function there is none, so Vue warns and never runs the hook.
  2. 2. How do you test that a composable removes its event listener when the component is destroyed?

    withSetup returns the app so you can unmount it, which runs onUnmounted. Then dispatch the event again and assert the state did not change.
  3. 3. What is the best way to deal with the network in a test for a data-fetching composable?

    Real requests are slow and flaky. A fake lets you test every path deterministically.
  4. 4. Two tests share one module-level store instance and the second fails depending on test order. What is the usual fix?

    Shared state leaks between tests. Fresh state per test removes the order dependence.
  5. 5. What does createTestingPinia do by default for actions?

    Actions are stubbed with spies (you provide createSpy: vi.fn), which isolates the component test from store logic.

Summary

  • Composables without hooks are plain functions: call them and read the returned refs.
  • withSetup mounts a tiny host component so hooks, inject and watchers work, and returns the app so you can test cleanup with unmount().
  • Fake the network (replace fetch or inject a fetcher) and cover success, HTTP errors, network errors and changed inputs; use flushPromises to let them settle.
  • Use fake timers for time-dependent code.
  • Keep store state isolated per test; with Pinia call setActivePinia(createPinia()) in beforeEach.
  • In component tests, createTestingPinia stubs actions so you test the component, not the store.

Next, find out what to do when things go wrong at runtime in Debugging Vue.