Vue.js testing utilities for Vue 3 applications providing component mounting, wrapper classes, and test utilities
—
Global configuration system for setting up consistent test environments, including component stubs, global properties, wrapper plugins, and default mounting options.
Central configuration object that provides default settings for all mount operations and wrapper behavior.
/**
* Global configuration object for Vue Test Utils
* Provides default settings applied to all mount operations
*/
interface Config {
/** Global mounting options applied to all mount calls */
global: GlobalConfigOptions;
/** Plugin system for extending wrapper functionality */
plugins: PluginConfig;
}
interface GlobalConfigOptions {
/** Default component stubs */
stubs: Record<string, Component | boolean | string>;
/** Default dependency injection values */
provide: Record<string | symbol, any>;
/** Default global components */
components: Record<string, Component>;
/** Default Vue app configuration */
config: Partial<AppConfig>;
/** Default global directives */
directives: Record<string, Directive>;
/** Default global mixins */
mixins: ComponentOptions[];
/** Default mock objects for global properties */
mocks: Record<string, any>;
/** Default Vue plugins */
plugins: Array<Plugin | [Plugin, ...any[]]>;
/** Whether stubs should render their default slot content */
renderStubDefaultSlot: boolean;
}
interface PluginConfig {
/** Plugins for VueWrapper instances */
VueWrapper: Array<(wrapper: VueWrapper<any>) => void>;
/** Plugins for DOMWrapper instances */
DOMWrapper: Array<(wrapper: DOMWrapper<any>) => void>;
/** Custom stub creation function */
createStubs?: (
stubs: Record<string, any>,
shallow: boolean
) => Record<string, Component>;
}
const config: Config;Usage Examples:
import { config } from "@vue/test-utils";
// Set global stubs
config.global.stubs = {
'router-link': true,
'transition': false,
'my-component': { template: '<div>Stubbed Component</div>' }
};
// Set global provide values
config.global.provide = {
theme: 'dark',
apiUrl: 'https://test-api.example.com'
};
// Set global components
config.global.components = {
'GlobalButton': ButtonComponent,
'GlobalIcon': IconComponent
};
// Set global plugins
config.global.plugins = [
router,
[store, { strict: false }]
];Configuration for automatically stubbing components during mounting to isolate testing.
/**
* Component stub configuration
* Controls how components are stubbed during shallow mounting or explicit stubbing
*/
type Stubs = Record<string, Component | boolean | string> | string[];
// Stub configuration options:
// true - Render as stub element with original tag name
// false - Render original component (no stubbing)
// string - Render as stub with custom tag name
// Component - Replace with custom component
// { template: string } - Replace with inline templateUsage Examples:
import { config } from "@vue/test-utils";
// Boolean stubbing
config.global.stubs = {
'child-component': true, // <child-component-stub>
'keep-original': false // renders original component
};
// String stubbing (custom tag names)
config.global.stubs = {
'complex-component': 'simple-stub' // <simple-stub>
};
// Component replacement
config.global.stubs = {
'third-party': MockThirdPartyComponent
};
// Template stubbing
config.global.stubs = {
'icon-component': {
template: '<span class="icon-stub">{{ $attrs.name }}</span>',
props: ['name']
}
};
// Array format (stub multiple components)
config.global.stubs = ['router-link', 'router-view', 'transition'];Configuration for providing values through Vue's dependency injection system.
/**
* Global provide configuration for dependency injection
* Makes values available to all mounted components via inject()
*/
interface ProvideConfig {
[key: string | symbol]: any;
}Usage Examples:
import { config } from "@vue/test-utils";
// String keys
config.global.provide = {
'api-client': mockApiClient,
'theme': 'dark',
'user-preferences': { language: 'en', timezone: 'UTC' }
};
// Symbol keys
const AuthKey = Symbol('auth');
config.global.provide = {
[AuthKey]: mockAuthService
};
// In components, these can be injected:
// const apiClient = inject('api-client');
// const auth = inject(AuthKey);Extensible plugin system for adding custom functionality to wrapper instances.
/**
* Install plugins for wrapper instances
* Plugins receive wrapper instance and can add methods or modify behavior
*/
interface PluginInstaller<T> {
(wrapper: T): void;
}
// VueWrapper plugins
config.plugins.VueWrapper.push((wrapper: VueWrapper<any>) => void);
// DOMWrapper plugins
config.plugins.DOMWrapper.push((wrapper: DOMWrapper<any>) => void);Usage Examples:
import { config } from "@vue/test-utils";
// Add custom method to VueWrapper
config.plugins.VueWrapper.push((wrapper) => {
wrapper.findByTestId = function(testId: string) {
return this.find(`[data-test-id="${testId}"]`);
};
});
// Add debugging helper to DOMWrapper
config.plugins.DOMWrapper.push((wrapper) => {
wrapper.debug = function() {
console.log('Element HTML:', this.html());
console.log('Element text:', this.text());
console.log('Element classes:', this.classes());
};
});
// Custom stub creation
config.plugins.createStubs = (stubs, shallow) => {
const customStubs = {};
for (const [key, value] of Object.entries(stubs)) {
if (typeof value === 'string' && value.startsWith('custom:')) {
customStubs[key] = createCustomStub(value.slice(7));
} else {
customStubs[key] = value;
}
}
return customStubs;
};Vue application configuration overrides for testing environments.
/**
* Vue app configuration overrides
* Allows customizing Vue app behavior during testing
*/
interface AppConfigOverrides {
/** Custom error handler for component errors */
errorHandler?: (err: unknown, instance: ComponentPublicInstance | null, info: string) => void;
/** Custom warning handler for development warnings */
warnHandler?: (msg: string, instance: ComponentPublicInstance | null, trace: string) => void;
/** Global properties available on all component instances */
globalProperties?: Record<string, any>;
/** Whether to suppress all warnings */
isNativeTag?: (tag: string) => boolean;
/** Performance tracking configuration */
performance?: boolean;
}Usage Examples:
import { config } from "@vue/test-utils";
// Global properties
config.global.config.globalProperties = {
$t: (key: string) => `translated:${key}`,
$http: mockHttpClient,
$filters: {
currency: (value: number) => `$${value.toFixed(2)}`
}
};
// Custom error handling for tests
config.global.config.errorHandler = (err, instance, info) => {
console.error('Vue error in tests:', err, info);
throw err; // Re-throw to fail the test
};
// Suppress warnings in tests
config.global.config.warnHandler = () => {
// Suppress warnings
};Configuration for mocking global properties and methods.
/**
* Mock objects for global properties
* Replaces global properties with test doubles
*/
interface MockConfig {
[key: string]: any;
}Usage Examples:
import { config } from "@vue/test-utils";
// Mock Vue Router
config.global.mocks = {
$route: {
path: '/test',
params: { id: '123' },
query: { tab: 'details' }
},
$router: {
push: vi.fn(),
replace: vi.fn(),
go: vi.fn()
}
};
// Mock i18n
config.global.mocks = {
$t: (key: string, values?: Record<string, any>) => {
return values ? `${key}:${JSON.stringify(values)}` : key;
},
$tc: (key: string, count: number) => `${key}:${count}`
};Utility methods for managing configuration state between tests.
/**
* Reset global configuration to default state
* Usually called in test setup/teardown
*/
// Manual reset (implementation varies by test framework)
function resetConfig(): void {
config.global.stubs = {};
config.global.provide = {};
config.global.components = {};
config.global.config.globalProperties = {};
config.global.directives = {};
config.global.mixins = [];
config.global.mocks = {};
config.global.plugins = [];
config.global.renderStubDefaultSlot = false;
config.plugins.VueWrapper = [];
config.plugins.DOMWrapper = [];
}Usage Examples:
// Jest setup
beforeEach(() => {
// Reset config before each test
resetConfig();
});
// Vitest setup
import { beforeEach } from 'vitest';
beforeEach(() => {
resetConfig();
});Configuration errors that may occur:
try {
config.global.stubs = {
'non-existent': NonExistentComponent
};
} catch (error) {
console.error('Stub configuration error:', error.message);
}Install with Tessl CLI
npx tessl i tessl/npm-vue--test-utils