Mocking Composables, Stores, and APIs
vi.mock(), mocking useFetch, mocking Pinia stores, mocking router in tests.
Why Mock?
Unit tests should isolate the component under test. Real network calls, real stores, and heavy composables make tests slow and flaky. Mocking replaces those dependencies with controllable fakes.
vi.fn: A Mock Function
vi.fn() creates a tracked function. You can inspect how it was called and control what it returns. It is the building block of all mocking.
import { vi } from "vitest"
const onSave = vi.fn()
onSave("draft")
expect(onSave).toHaveBeenCalledWith("draft")
expect(onSave).toHaveBeenCalledTimes(1)All lessons in this course
- Vitest Setup for Vue Projects
- Mounting and Querying Components
- Testing User Interactions and Events
- Mocking Composables, Stores, and APIs