Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 38 ยท Testing Stores

Mocking Actions and APIs in Pinia Tests

Keep Pinia tests fast and reliable: inject the API client, mock modules with vi.mock, fake timers and responses, and test stores that call other stores.

Real stores talk to the outside world: HTTP APIs, storage, timers, other stores. A good unit test cuts those connections and replaces them with something it controls. This lesson covers three ways to do that, from the most explicit to the most magical, and ends with testing a store that uses another store.

Strategy 1: inject the dependency

The simplest, most test-friendly design is to keep the API client in its own module and let the store receive it, or to make it replaceable. For a plugin-based app you can attach it with a plugin (store.api), which tests can replace:

JavaScript
// the store
actions: {
  async load() {
    this.items = await this.api.getItems();
  },
},
JavaScript
// in a test
const pinia = createPinia();
pinia.use(() => ({ api: { getItems: async () => [{ id: 1 }] } }));
createApp({}).use(pinia);   // plugins only run once pinia is installed on an app
setActivePinia(pinia);

A plugin registered with pinia.use() is queued until the pinia is installed on an app. In a test with no component, install it on an empty app (createApp({}).use(pinia)) or the plugin never runs and store.api is undefined. createTestingPinia does this for you.

The test supplies a fake api. No mocking library is needed, and the store's code stays plain. In a real app the same plugin supplies the real client. Use this when you control the architecture.

Strategy 2: mock the module

Often the store imports the API function directly:

JavaScript
import { fetchProducts } from "../api/products";

export const useProductsStore = defineStore("products", {
  state: () => ({ list: [], error: null }),
  actions: {
    async load() {
      try {
        this.list = await fetchProducts();
      } catch (e) {
        this.error = e.message;
      }
    },
  },
});

Vitest replaces that module for the whole test file with vi.mock:

JavaScript
import { vi, it, expect, beforeEach } from "vitest";
import { setActivePinia, createPinia } from "pinia";
import { fetchProducts } from "../api/products";
import { useProductsStore } from "./products";

vi.mock("../api/products");          // every export becomes a mock function

beforeEach(() => setActivePinia(createPinia()));

it("stores the loaded products", async () => {
  vi.mocked(fetchProducts).mockResolvedValue([{ id: 1, name: "Pen" }]);
  const store = useProductsStore();
  await store.load();
  expect(store.list).toEqual([{ id: 1, name: "Pen" }]);
  expect(fetchProducts).toHaveBeenCalledTimes(1);
});

it("stores the error message", async () => {
  vi.mocked(fetchProducts).mockRejectedValue(new Error("offline"));
  const store = useProductsStore();
  await store.load();
  expect(store.error).toBe("offline");
});

mockResolvedValue and mockRejectedValue set what the fake returns for that test. toHaveBeenCalledWith checks arguments. Jest has the same API with jest.mock. (This needs a bundler and test runner, so the code is read-only here.)

Strategy 3: spy on global functions

If the store calls fetch directly, replace the global in the test with vi.stubGlobal("fetch", vi.fn(...)) and restore it afterwards with vi.unstubAllGlobals(). It works but couples the test to how the request is made. Prefer strategies 1 or 2 when you can.

Live: a store with a replaceable client

Here is strategy 1 at work in the browser. The same store is run against three fake clients (success, failure and slow) and checks both the result and how many calls were made. The "mock" is a plain spy function.

Injecting a fake API client

The third case uses a gate: a promise the test resolves by hand. That is the trick for asserting on intermediate states without real delays.

Fake timers

Stores with debouncing, polling or delays should not make tests wait. Vitest's vi.useFakeTimers() lets you advance time instantly:

JavaScript
vi.useFakeTimers();
store.startPolling();
await vi.advanceTimersByTimeAsync(5000);
expect(api.poll).toHaveBeenCalledTimes(5);
vi.useRealTimers();

A store that uses another store

Stores can use other stores inside actions. The test then needs both. With a fresh active pinia, calling useOtherStore() in the test creates the other store in the same pinia, so you can seed it:

JavaScript
it("applies the user's discount", () => {
  const user = useUserStore();
  user.$patch({ discount: 0.2 });

  const cart = useCartStore();
  cart.add({ id: 1, price: 10 });
  expect(cart.totalWithDiscount).toBe(8);
});

This tests the real interaction. If the other store is slow or complicated, use createTestingPinia with initialState to seed it instead, as in the previous lesson.

Run it, then try the second check live:

Two stores in one pinia

Rules of thumb

  • Fresh pinia per test; fresh mocks per test (vi.clearAllMocks() or restoreMocks: true).
  • Mock at the boundary (HTTP client, storage), not inside your own store.
  • Test the error path as often as the happy path.
  • Prefer assertions on state and calls over assertions on timing.
  • One behavior per test, with a name that states it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does vi.mock('../api/products') do?

    vi.mock automocks the module so you can set return values per test.
  2. 2. How do you make a mocked function return a rejected promise?

    mockRejectedValue makes the mock return a promise that rejects with the given error.
  3. 3. A 'gate' promise in a test lets you...

    The test resolves the gate manually, so it can assert on loading flags before and after.
  4. 4. To test a store that uses another store, you should...

    Stores share the active pinia, so useOtherStore() in the test returns the same instance the action uses.

Summary

  • Cut the store off from the outside world: inject the client, mock the module or stub globals.
  • vi.mock, mockResolvedValue and mockRejectedValue set up success and failure.
  • A gate promise and fake timers let you test pending states without waiting.
  • Stores that use other stores are tested in one active pinia, seeding the other store.
  • Test both the happy path and the error path.

Next: SSR and Hydration Basics