0
0
Vueframework~3 mins

Why Mocking composables and stores in Vue? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could test your Vue components without waiting for slow API calls or worrying about complex state?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
import { useStore } from '@/stores';
// real store used in test
const store = useStore();
// test depends on real store state and API calls
After
vi.mock('@/stores', () => ({
  useStore: () => ({
    state: { count: 5 },
    increment: vi.fn()
  })
}));
// test uses mocked store with controlled state and functions
What It Enables

It enables writing fast, reliable tests that focus only on the component's behavior without side effects from real data or logic.

Real Life Example

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.

Key Takeaways

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.