Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 38 ยท Testing Stores

Testing Pinia Stores with Vitest

Learn to unit-test Pinia stores without a component: create a fresh pinia per test, call actions, assert state and getters, and test async actions and setup stores.

A store is just a function that returns an object, which makes it one of the easiest parts of a Vue app to test. There is no template, no router and no DOM involved: create a store, call an action, check the state. In this lesson you learn the one trick that makes it work (an active pinia), the structure of a good store test and how to handle async actions. The next two lessons cover components and mocking.

The one thing you need: an active pinia

Calling useCounterStore() outside a component requires an active pinia: an instance Pinia can attach the store to. Inside a running app, app.use(pinia) provides it. In a test there is no app, so you create one yourself and mark it active:

JavaScript
import { setActivePinia, createPinia } from "pinia";
import { beforeEach, describe, expect, it } from "vitest";
import { useCounterStore } from "../stores/counter";

describe("counter store", () => {
  beforeEach(() => {
    setActivePinia(createPinia());
  });

  it("increments", () => {
    const counter = useCounterStore();
    expect(counter.count).toBe(0);
    counter.increment();
    expect(counter.count).toBe(1);
  });
});

The key line is beforeEach(() => setActivePinia(createPinia())). A fresh pinia per test means a fresh store per test, so no test can leak state into the next. Without it, a counter changed by test 1 would start test 2 at 1 and tests would pass or fail depending on their order, the classic flaky-test pattern.

Vitest, Jest and any other runner work the same way. The Pinia part is only setActivePinia(createPinia()).

What to test

Test the behavior of the store, not its internals:

  • Initial state: sensible defaults.
  • Actions: after calling them, state is what you expect.
  • Getters: computed values for different states.
  • Edge cases: empty lists, errors, duplicates.

Avoid asserting on how an action is written. If you rewrite increment to use $patch, the test should still pass.

A runnable test run

The live editor below cannot run Vitest (it needs Node and a bundler), so it includes a tiny stand-in test runner of about fifteen lines with describe, it, beforeEach and expect().toBe(). The stores and Pinia are real; only the runner is a stand-in. Read the tests, then run them and break one on purpose.

Unit tests for a cart store (real Pinia, tiny runner)

All five pass. Now change found.qty++ to found.qty += 2 and run again: two tests fail with a clear message. That feedback loop is the reason to test stores.

Testing async actions

Actions that call an API return promises. Test them by awaiting the action, then checking the state. The important rule: never call the real network in a unit test. Give the store a way to receive its data source, or mock it (the mocking lesson shows several options).

JavaScript
it("loads users", async () => {
  const users = useUsersStore();
  await users.load();
  expect(users.list.length).toBe(2);
  expect(users.loading).toBe(false);
});

Check both the happy path and the failure path, and the loading flag in between:

Testing loading and error states of an async action

The third test swaps the data source for one that throws. That is the heart of store testing: control the inputs, assert the outputs.

Testing setup stores and getters

Setup stores work with exactly the same test code. A getter or a computed is read like a property. To test a getter for several states, set state directly or with $patch:

JavaScript
it("computes the total", () => {
  const cart = useCartStore();
  cart.$patch({ items: [{ id: 1, price: 5, qty: 2 }] });
  expect(cart.total).toBe(10);
});

Setting up state this way is faster and clearer than calling actions repeatedly when you only care about the getter.

Resetting between tests

Besides creating a new pinia, you can call store.$reset() in options stores. A new pinia per test is more reliable because it also works for setup stores (where $reset is not available) and clears all stores at once.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why call setActivePinia(createPinia()) in beforeEach?

    A new pinia per test creates a new store instance, so one test cannot affect another.
  2. 2. Which is the best thing to assert in a store test?

    Test observable behavior: state, getters and results. That keeps tests valid when you refactor.
  3. 3. A store action calls fetch. What should a unit test do?

    Unit tests must not depend on the network; replace or mock the data source.
  4. 4. How do you await an async action in a test?

    Actions return the promise from their body, so await it and then assert.

Summary

  • Use setActivePinia(createPinia()) in beforeEach to get fresh stores per test.
  • Test state, getters and actions through the store's public interface.
  • await async actions; test success, failure and loading flags.
  • Control the data source so tests never hit the network.
  • Setup stores and options stores are tested the same way.

Next: Testing Components with createTestingPinia