What if you could test your Vue components without waiting for slow API calls or worrying about complex state?
Why Mocking composables and stores in Vue? - Purpose & Use Cases
Imagine testing a Vue component that uses several composables and stores to manage data and state. You try to test it by running the full app logic every time, including API calls and complex state changes.
Manually running all real composables and stores in tests is slow, unreliable, and makes tests hard to isolate. It's like trying to test a single light bulb by turning on the whole house's electricity--too much noise and risk of errors.
Mocking composables and stores lets you replace real implementations with simple, controlled versions during tests. This makes tests faster, clearer, and focused only on what you want to check.
import { useStore } from '@/stores'; // real store used in test const store = useStore(); // test depends on real store state and API calls
vi.mock('@/stores', () => ({ useStore: () => ({ state: { count: 5 }, increment: vi.fn() }) })); // test uses mocked store with controlled state and functions
It enables writing fast, reliable tests that focus only on the component's behavior without side effects from real data or logic.
When building a shopping cart, you can mock the cart store in tests to simulate adding items without calling real APIs or changing actual app state.
Manual testing with real composables and stores is slow and fragile.
Mocking replaces complex logic with simple, controlled versions for tests.
This leads to faster, clearer, and more reliable tests.