0
# Global Configuration
1
2
Global configuration system for setting up consistent test environments, including component stubs, global properties, wrapper plugins, and default mounting options.
3
4
## Capabilities
5
6
### Global Configuration Object
7
8
Central configuration object that provides default settings for all mount operations and wrapper behavior.
9
10
```typescript { .api }
11
/**
12
* Global configuration object for Vue Test Utils
13
* Provides default settings applied to all mount operations
14
*/
15
interface Config {
16
/** Global mounting options applied to all mount calls */
17
global: GlobalConfigOptions;
18
/** Plugin system for extending wrapper functionality */
19
plugins: PluginConfig;
20
}
21
22
interface GlobalConfigOptions {
23
/** Default component stubs */
24
stubs: Record<string, Component | boolean | string>;
25
/** Default dependency injection values */
26
provide: Record<string | symbol, any>;
27
/** Default global components */
28
components: Record<string, Component>;
29
/** Default Vue app configuration */
30
config: Partial<AppConfig>;
31
/** Default global directives */
32
directives: Record<string, Directive>;
33
/** Default global mixins */
34
mixins: ComponentOptions[];
35
/** Default mock objects for global properties */
36
mocks: Record<string, any>;
37
/** Default Vue plugins */
38
plugins: Array<Plugin | [Plugin, ...any[]]>;
39
/** Whether stubs should render their default slot content */
40
renderStubDefaultSlot: boolean;
41
}
42
43
interface PluginConfig {
44
/** Plugins for VueWrapper instances */
45
VueWrapper: Array<(wrapper: VueWrapper<any>) => void>;
46
/** Plugins for DOMWrapper instances */
47
DOMWrapper: Array<(wrapper: DOMWrapper<any>) => void>;
48
/** Custom stub creation function */
49
createStubs?: (
50
stubs: Record<string, any>,
51
shallow: boolean
52
) => Record<string, Component>;
53
}
54
55
const config: Config;
56
```
57
58
**Usage Examples:**
59
60
```typescript
61
import { config } from "@vue/test-utils";
62
63
// Set global stubs
64
config.global.stubs = {
65
'router-link': true,
66
'transition': false,
67
'my-component': { template: '<div>Stubbed Component</div>' }
68
};
69
70
// Set global provide values
71
config.global.provide = {
72
theme: 'dark',
73
apiUrl: 'https://test-api.example.com'
74
};
75
76
// Set global components
77
config.global.components = {
78
'GlobalButton': ButtonComponent,
79
'GlobalIcon': IconComponent
80
};
81
82
// Set global plugins
83
config.global.plugins = [
84
router,
85
[store, { strict: false }]
86
];
87
```
88
89
### Component Stubbing
90
91
Configuration for automatically stubbing components during mounting to isolate testing.
92
93
```typescript { .api }
94
/**
95
* Component stub configuration
96
* Controls how components are stubbed during shallow mounting or explicit stubbing
97
*/
98
type Stubs = Record<string, Component | boolean | string> | string[];
99
100
// Stub configuration options:
101
// true - Render as stub element with original tag name
102
// false - Render original component (no stubbing)
103
// string - Render as stub with custom tag name
104
// Component - Replace with custom component
105
// { template: string } - Replace with inline template
106
```
107
108
**Usage Examples:**
109
110
```typescript
111
import { config } from "@vue/test-utils";
112
113
// Boolean stubbing
114
config.global.stubs = {
115
'child-component': true, // <child-component-stub>
116
'keep-original': false // renders original component
117
};
118
119
// String stubbing (custom tag names)
120
config.global.stubs = {
121
'complex-component': 'simple-stub' // <simple-stub>
122
};
123
124
// Component replacement
125
config.global.stubs = {
126
'third-party': MockThirdPartyComponent
127
};
128
129
// Template stubbing
130
config.global.stubs = {
131
'icon-component': {
132
template: '<span class="icon-stub">{{ $attrs.name }}</span>',
133
props: ['name']
134
}
135
};
136
137
// Array format (stub multiple components)
138
config.global.stubs = ['router-link', 'router-view', 'transition'];
139
```
140
141
### Dependency Injection
142
143
Configuration for providing values through Vue's dependency injection system.
144
145
```typescript { .api }
146
/**
147
* Global provide configuration for dependency injection
148
* Makes values available to all mounted components via inject()
149
*/
150
interface ProvideConfig {
151
[key: string | symbol]: any;
152
}
153
```
154
155
**Usage Examples:**
156
157
```typescript
158
import { config } from "@vue/test-utils";
159
160
// String keys
161
config.global.provide = {
162
'api-client': mockApiClient,
163
'theme': 'dark',
164
'user-preferences': { language: 'en', timezone: 'UTC' }
165
};
166
167
// Symbol keys
168
const AuthKey = Symbol('auth');
169
config.global.provide = {
170
[AuthKey]: mockAuthService
171
};
172
173
// In components, these can be injected:
174
// const apiClient = inject('api-client');
175
// const auth = inject(AuthKey);
176
```
177
178
### Plugin System
179
180
Extensible plugin system for adding custom functionality to wrapper instances.
181
182
```typescript { .api }
183
/**
184
* Install plugins for wrapper instances
185
* Plugins receive wrapper instance and can add methods or modify behavior
186
*/
187
interface PluginInstaller<T> {
188
(wrapper: T): void;
189
}
190
191
// VueWrapper plugins
192
config.plugins.VueWrapper.push((wrapper: VueWrapper<any>) => void);
193
194
// DOMWrapper plugins
195
config.plugins.DOMWrapper.push((wrapper: DOMWrapper<any>) => void);
196
```
197
198
**Usage Examples:**
199
200
```typescript
201
import { config } from "@vue/test-utils";
202
203
// Add custom method to VueWrapper
204
config.plugins.VueWrapper.push((wrapper) => {
205
wrapper.findByTestId = function(testId: string) {
206
return this.find(`[data-test-id="${testId}"]`);
207
};
208
});
209
210
// Add debugging helper to DOMWrapper
211
config.plugins.DOMWrapper.push((wrapper) => {
212
wrapper.debug = function() {
213
console.log('Element HTML:', this.html());
214
console.log('Element text:', this.text());
215
console.log('Element classes:', this.classes());
216
};
217
});
218
219
// Custom stub creation
220
config.plugins.createStubs = (stubs, shallow) => {
221
const customStubs = {};
222
for (const [key, value] of Object.entries(stubs)) {
223
if (typeof value === 'string' && value.startsWith('custom:')) {
224
customStubs[key] = createCustomStub(value.slice(7));
225
} else {
226
customStubs[key] = value;
227
}
228
}
229
return customStubs;
230
};
231
```
232
233
### App Configuration
234
235
Vue application configuration overrides for testing environments.
236
237
```typescript { .api }
238
/**
239
* Vue app configuration overrides
240
* Allows customizing Vue app behavior during testing
241
*/
242
interface AppConfigOverrides {
243
/** Custom error handler for component errors */
244
errorHandler?: (err: unknown, instance: ComponentPublicInstance | null, info: string) => void;
245
/** Custom warning handler for development warnings */
246
warnHandler?: (msg: string, instance: ComponentPublicInstance | null, trace: string) => void;
247
/** Global properties available on all component instances */
248
globalProperties?: Record<string, any>;
249
/** Whether to suppress all warnings */
250
isNativeTag?: (tag: string) => boolean;
251
/** Performance tracking configuration */
252
performance?: boolean;
253
}
254
```
255
256
**Usage Examples:**
257
258
```typescript
259
import { config } from "@vue/test-utils";
260
261
// Global properties
262
config.global.config.globalProperties = {
263
$t: (key: string) => `translated:${key}`,
264
$http: mockHttpClient,
265
$filters: {
266
currency: (value: number) => `$${value.toFixed(2)}`
267
}
268
};
269
270
// Custom error handling for tests
271
config.global.config.errorHandler = (err, instance, info) => {
272
console.error('Vue error in tests:', err, info);
273
throw err; // Re-throw to fail the test
274
};
275
276
// Suppress warnings in tests
277
config.global.config.warnHandler = () => {
278
// Suppress warnings
279
};
280
```
281
282
### Mock Objects
283
284
Configuration for mocking global properties and methods.
285
286
```typescript { .api }
287
/**
288
* Mock objects for global properties
289
* Replaces global properties with test doubles
290
*/
291
interface MockConfig {
292
[key: string]: any;
293
}
294
```
295
296
**Usage Examples:**
297
298
```typescript
299
import { config } from "@vue/test-utils";
300
301
// Mock Vue Router
302
config.global.mocks = {
303
$route: {
304
path: '/test',
305
params: { id: '123' },
306
query: { tab: 'details' }
307
},
308
$router: {
309
push: vi.fn(),
310
replace: vi.fn(),
311
go: vi.fn()
312
}
313
};
314
315
// Mock i18n
316
config.global.mocks = {
317
$t: (key: string, values?: Record<string, any>) => {
318
return values ? `${key}:${JSON.stringify(values)}` : key;
319
},
320
$tc: (key: string, count: number) => `${key}:${count}`
321
};
322
```
323
324
## Configuration Reset
325
326
Utility methods for managing configuration state between tests.
327
328
```typescript { .api }
329
/**
330
* Reset global configuration to default state
331
* Usually called in test setup/teardown
332
*/
333
// Manual reset (implementation varies by test framework)
334
function resetConfig(): void {
335
config.global.stubs = {};
336
config.global.provide = {};
337
config.global.components = {};
338
config.global.config.globalProperties = {};
339
config.global.directives = {};
340
config.global.mixins = [];
341
config.global.mocks = {};
342
config.global.plugins = [];
343
config.global.renderStubDefaultSlot = false;
344
config.plugins.VueWrapper = [];
345
config.plugins.DOMWrapper = [];
346
}
347
```
348
349
**Usage Examples:**
350
351
```typescript
352
// Jest setup
353
beforeEach(() => {
354
// Reset config before each test
355
resetConfig();
356
});
357
358
// Vitest setup
359
import { beforeEach } from 'vitest';
360
361
beforeEach(() => {
362
resetConfig();
363
});
364
```
365
366
## Error Handling
367
368
Configuration errors that may occur:
369
370
- **Invalid Stub**: When stub configuration references non-existent components
371
- **Plugin Error**: When plugins throw errors during wrapper creation
372
- **Provide Error**: When provide values cause injection conflicts
373
- **App Config Error**: When app configuration overrides cause Vue errors
374
375
```typescript
376
try {
377
config.global.stubs = {
378
'non-existent': NonExistentComponent
379
};
380
} catch (error) {
381
console.error('Stub configuration error:', error.message);
382
}
383
```