javascript / expert
Snippet
Mocking Injected Dependencies in Component Tests
When testing components that rely on `inject`, you must simulate the provider. Vue Test Utils allows you to inject mocks via the `global.provide` option, isolating the component from real API calls or complex global state.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { mount } from '@vue/test-utils';import { ApiServiceKey } from '@/keys';test('renders data from API', async () => {const mockApi = { fetchData: vi.fn(() => Promise.resolve('Data')) };const wrapper = mount(MyComponent, {global: {provide: {[ApiServiceKey]: mockApi}}});// Assertions...});
vue
Breakdown
1
const mockApi = { fetchData: vi.fn(...) };
Create a spy or mock object that mimics the expected interface of the service.
2
mount(MyComponent, { global: { provide: { ... } } });
Mount the component while supplying the mock implementation for the specified Symbol key.
3
[ApiServiceKey]: mockApi
Use computed property syntax to map the Symbol key to your mock implementation.