Bird
Raised Fist0
Vueframework~20 mins

Mocking composables and stores in Vue - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Mocking Mastery in Vue
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output when mocking a composable's return value?

Given a Vue component that uses a composable returning a reactive count, and the composable is mocked to return a fixed count, what will the component render?

Vue
/* Composable: useCounter.js */
import { ref } from 'vue';
export function useCounter() {
  const count = ref(0);
  function increment() { count.value++; }
  return { count, increment };
}

/* Component: CounterDisplay.vue */
<template>
  <div>{{ count }}</div>
</template>
<script setup>
import { useCounter } from './useCounter';
const { count } = useCounter();
</script>

/* Test file snippet */
vi.mock('./useCounter', () => ({
  useCounter: () => ({ count: 42 })
}));
AThe component throws a runtime error due to missing ref wrapper.
BThe component renders '0' because the mock does not update reactivity.
CThe component renders '42' as the count value.
DThe component renders 'undefined' because count is not reactive.
Attempts:
2 left
💡 Hint

Think about what the mock returns and how the component uses it.

🔧 Debug
intermediate
2:00remaining
Why does mocking a Pinia store's state fail with a TypeError?

In a test, mocking a Pinia store's state directly causes a TypeError: Cannot read property 'value' of undefined. What is the likely cause?

Vue
import { setActivePinia, createPinia } from 'pinia';
import { useUserStore } from '@/stores/user';

setActivePinia(createPinia());

vi.mock('@/stores/user', () => ({
  useUserStore: () => ({
    state: { name: 'Alice' }
  })
}));

const store = useUserStore();
console.log(store.name);
AThe mock returns a plain object instead of a reactive store, so accessing reactive properties fails.
BPinia stores cannot be mocked at all, causing all mocks to fail.
CThe test environment lacks a proper Vue instance, causing reactivity errors.
DThe store is not registered in Pinia, so useUserStore returns undefined.
Attempts:
2 left
💡 Hint

Consider how Pinia stores expose state and reactivity.

📝 Syntax
advanced
2:00remaining
Which mock setup correctly mocks a composable returning a reactive ref?

Choose the correct way to mock a composable that returns a reactive ref count initialized to 10.

Vue
/* Original composable: useCount.js */
import { ref } from 'vue';
export function useCount() {
  const count = ref(0);
  return { count };
}
Avi.mock('./useCount', () => ({ useCount: () => ({ count: 10 }) }));
Bvi.mock('./useCount', () => ({ useCount: () => ({ count: computed(() => 10) }) }));
Cvi.mock('./useCount', () => ({ useCount: () => ({ count: reactive(10) }) }));
Dvi.mock('./useCount', () => ({ useCount: () => ({ count: ref(10) }) }));
Attempts:
2 left
💡 Hint

Remember how the original composable returns a ref.

❓ state_output
advanced
2:00remaining
What is the value of store.count after mocking and incrementing?

Given a Pinia store with a count state and an increment action, if the store is mocked to start with count = 5, what is the value of count after calling increment() once?

Vue
/* Store definition */
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  actions: {
    increment() { this.count++; }
  }
});

/* Test mock */
vi.mock('@/stores/counter', () => ({
  useCounterStore: () => ({
    count: 5,
    increment() { this.count++; }
  })
}));

const store = useCounterStore();
store.increment();
const result = store.count;
A5
B6
CNaN
Dundefined
Attempts:
2 left
💡 Hint

Check how the mocked increment method modifies the count property.

🧠 Conceptual
expert
3:00remaining
Why is it important to mock composables with the same reactive structure as originals?

When mocking Vue composables or Pinia stores, why must the mock preserve the original's reactive structure (e.g., refs, reactive objects) instead of returning plain values?

ABecause Vue components rely on reactivity to update the UI, and mocks without reactive wrappers break this, causing stale or missing updates.
BBecause plain values cause syntax errors in Vue templates when used inside components.
CBecause testing frameworks require all mocks to be reactive to run tests successfully.
DBecause only reactive objects can be imported in Vue components without errors.
Attempts:
2 left
💡 Hint

Think about how Vue tracks changes to update the screen.

Practice

(1/5)
1. What is the main reason to mock composables or stores in Vue component tests?
easy
A. To automatically generate UI snapshots
B. To improve the component's runtime performance
C. To isolate the component test from real logic and external dependencies
D. To enable two-way data binding in tests

Solution

  1. Step 1: Understand the purpose of mocking

    Mocking replaces real implementations with fake ones to isolate tests from external logic.
  2. Step 2: Apply this to composables and stores

    Mocking composables and stores prevents side effects and focuses tests on the component itself.
  3. Final Answer:

    To isolate the component test from real logic and external dependencies -> Option C
  4. Quick Check:

    Mocking isolates tests = A [OK]
Hint: Mock to isolate component logic from external code [OK]
Common Mistakes:
  • Thinking mocking improves runtime performance
  • Confusing mocking with UI snapshot generation
  • Believing mocking enables data binding
2. Which syntax correctly mocks a composable module named useAuth using Vitest's vi.mock()?
easy
A. vi.mock('./useAuth', () => ({ useAuth: () => ({ isLoggedIn: true }) }))
B. vi.mock('useAuth', () => ({ isLoggedIn: true }))
C. vi.mock('useAuth', () => ({ useAuth: () => ({ isLoggedIn: true }) }))
D. vi.mock('./useAuth', () => ({ isLoggedIn: true }))

Solution

  1. Step 1: Identify the module path

    Modules are mocked by their relative or absolute path, so './useAuth' is correct if the file is local.
  2. Step 2: Provide a factory returning the mocked composable function

    The factory must return an object with the composable function that returns the mocked state.
  3. Final Answer:

    vi.mock('./useAuth', () => ({ useAuth: () => ({ isLoggedIn: true }) })) -> Option A
  4. Quick Check:

    Correct path and factory function = C [OK]
Hint: Mock with correct path and return a function for composables [OK]
Common Mistakes:
  • Using module name without path when path is required
  • Returning state object directly instead of a function
  • Mocking without a factory function
3. Given this mocked store code snippet:
vi.mock('./store', () => ({ useStore: () => ({ count: 5, increment: vi.fn() }) }))

const store = useStore();
store.increment();
console.log(store.count);

What will be logged to the console?
medium
A. undefined
B. 5
C. Error: increment is not a function
D. 0

Solution

  1. Step 1: Analyze the mocked store return values

    The mocked useStore returns an object with count: 5 and increment as a mock function.
  2. Step 2: Check the console.log output

    The count property is 5 and is not changed by calling increment() because it's a mock function without implementation.
  3. Final Answer:

    5 -> Option B
  4. Quick Check:

    Mocked count value logged = 5 [OK]
Hint: Mocked state stays same unless mock function changes it [OK]
Common Mistakes:
  • Assuming mock function changes state automatically
  • Expecting undefined because increment is mocked
  • Confusing mock function with real implementation
4. Identify the error in this test mocking a composable:
vi.mock('./useCounter', () => ({
  useCounter: {
    count: 0,
    increment: vi.fn()
  }
}))
medium
A. The mock should return a function, not an object directly
B. The vi.fn() should be replaced with a real function
C. The module path './useCounter' is incorrect
D. The mock should not include the increment function

Solution

  1. Step 1: Understand composable mocking pattern

    Composable modules export functions, so mocks must return a function, not an object.
  2. Step 2: Identify the incorrect mock structure

    The code returns an object directly instead of a function returning the object.
  3. Final Answer:

    The mock should return a function, not an object directly -> Option A
  4. Quick Check:

    Composable mocks return functions = D [OK]
Hint: Mock composables as functions returning objects [OK]
Common Mistakes:
  • Returning object directly instead of function
  • Replacing vi.fn() unnecessarily
  • Incorrect module path assumptions
5. You want to test a Vue component that uses a Pinia store with a fetchData action. How do you mock the store to verify fetchData is called without running its real logic?
hard
A. Replace fetchData with an empty async function in the real store
B. Import the real store and spy on fetchData without mocking
C. Mock the component instead of the store
D. Use vi.mock() to replace the store module with a mock where fetchData is a vi.fn()

Solution

  1. Step 1: Understand mocking for store actions

    To isolate tests, replace the store module with a mock that has fetchData as a mock function.
  2. Step 2: Use vi.mock() to replace the store module

    This allows you to track calls to fetchData without executing its real code.
  3. Final Answer:

    Use vi.mock() to replace the store module with a mock where fetchData is a vi.fn() -> Option D
  4. Quick Check:

    Mock store action with vi.fn() = A [OK]
Hint: Mock store actions with vi.fn() to track calls without side effects [OK]
Common Mistakes:
  • Not mocking the store and calling real logic
  • Mocking the component instead of the store
  • Replacing functions with empty but untracked implementations
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard