0
# Vue Component Wrapper
1
2
The VueWrapper class provides methods for interacting with mounted Vue components, including prop manipulation, event testing, component state inspection, and lifecycle management.
3
4
## Capabilities
5
6
### Component Instance Access
7
8
Direct access to the Vue component instance with setup state proxy for Composition API components.
9
10
```typescript { .api }
11
/**
12
* The Vue component instance with setup state proxy
13
* Provides access to component data, methods, computed properties, and exposed values
14
*/
15
readonly vm: ComponentPublicInstance;
16
```
17
18
**Usage Examples:**
19
20
```typescript
21
import { mount } from "@vue/test-utils";
22
23
const wrapper = mount(MyComponent);
24
25
// Access component data and methods
26
console.log(wrapper.vm.message);
27
wrapper.vm.handleClick();
28
29
// Access computed properties
30
expect(wrapper.vm.computedValue).toBe("expected");
31
32
// Access exposed values (script setup)
33
expect(wrapper.vm.exposedMethod).toBeDefined();
34
```
35
36
### Props Management
37
38
Methods for inspecting and updating component props dynamically during tests.
39
40
```typescript { .api }
41
/**
42
* Get all component props or a specific prop value
43
* @param key - Optional prop key to retrieve specific value
44
* @returns All props object or specific prop value
45
*/
46
props(): Record<string, any>;
47
props(key: string): any;
48
49
/**
50
* Update component props and trigger reactivity
51
* @param props - Props object to merge with existing props
52
* @returns Promise that resolves after props update and re-render
53
*/
54
setProps(props: Record<string, any>): Promise<void>;
55
```
56
57
**Usage Examples:**
58
59
```typescript
60
const wrapper = mount(MyComponent, {
61
props: { title: "Initial", count: 0 }
62
});
63
64
// Get all props
65
const allProps = wrapper.props();
66
expect(allProps).toEqual({ title: "Initial", count: 0 });
67
68
// Get specific prop
69
expect(wrapper.props("title")).toBe("Initial");
70
71
// Update props
72
await wrapper.setProps({ title: "Updated", count: 5 });
73
expect(wrapper.props("title")).toBe("Updated");
74
```
75
76
### Event Testing
77
78
Methods for testing component events, including emitted events history and validation.
79
80
```typescript { .api }
81
/**
82
* Get all emitted events or events for a specific event name
83
* @param eventName - Optional event name to filter results
84
* @returns All emitted events or filtered events array
85
*/
86
emitted(): Record<string, unknown[][]>;
87
emitted<T = unknown[]>(eventName: string): T[];
88
```
89
90
**Usage Examples:**
91
92
```typescript
93
const wrapper = mount(MyComponent);
94
95
// Trigger an action that emits events
96
await wrapper.find('button').trigger('click');
97
98
// Get all emitted events
99
const allEvents = wrapper.emitted();
100
console.log(allEvents); // { click: [[]], input: [["value"]] }
101
102
// Get specific event
103
const clickEvents = wrapper.emitted('click');
104
expect(clickEvents).toHaveLength(1);
105
106
// Check event payload
107
const inputEvents = wrapper.emitted('input');
108
expect(inputEvents[0]).toEqual(["expected payload"]);
109
```
110
111
### Data Management
112
113
Methods for inspecting and updating component data state.
114
115
```typescript { .api }
116
/**
117
* Update component data and trigger reactivity
118
* @param data - Data object to merge with existing component data
119
* @returns Promise that resolves after data update and re-render
120
*/
121
setData(data: Record<string, any>): Promise<void>;
122
```
123
124
**Usage Examples:**
125
126
```typescript
127
const wrapper = mount(MyComponent);
128
129
// Update component data
130
await wrapper.setData({
131
message: "New message",
132
isActive: true
133
});
134
135
// Verify data changes
136
expect(wrapper.vm.message).toBe("New message");
137
expect(wrapper.text()).toContain("New message");
138
```
139
140
### Form Input Interaction
141
142
Method for setting values on form inputs and triggering appropriate events.
143
144
```typescript { .api }
145
/**
146
* Set value on form inputs and emit appropriate events (input, change)
147
* @param value - Value to set on the element
148
* @returns Promise that resolves after value is set and events are emitted
149
*/
150
setValue(value: any): Promise<void>;
151
```
152
153
**Usage Examples:**
154
155
```typescript
156
const wrapper = mount(MyComponent);
157
158
// Set input value
159
await wrapper.find('input[type="text"]').setValue("test value");
160
161
// Set checkbox state
162
await wrapper.find('input[type="checkbox"]').setValue(true);
163
164
// Set select value
165
await wrapper.find('select').setValue("option2");
166
```
167
168
### Component Lifecycle
169
170
Methods for managing component lifecycle and cleanup.
171
172
```typescript { .api }
173
/**
174
* Unmount the component and perform cleanup
175
* Triggers beforeUnmount and unmounted lifecycle hooks
176
*/
177
unmount(): void;
178
179
/**
180
* Check if the component still exists and is mounted
181
* @returns true if component is still mounted, false otherwise
182
*/
183
exists(): boolean;
184
185
/**
186
* Get the internal component instance
187
* @returns Vue internal component instance
188
*/
189
getCurrentComponent(): ComponentInternalInstance;
190
```
191
192
**Usage Examples:**
193
194
```typescript
195
const wrapper = mount(MyComponent);
196
197
// Check if component exists
198
expect(wrapper.exists()).toBe(true);
199
200
// Access internal component instance
201
const instance = wrapper.getCurrentComponent();
202
console.log(instance.uid);
203
204
// Unmount component
205
wrapper.unmount();
206
expect(wrapper.exists()).toBe(false);
207
```
208
209
### Visibility Testing
210
211
Method for checking component visibility in the DOM.
212
213
```typescript { .api }
214
/**
215
* Check if the component is visible in the DOM
216
* Considers CSS display, visibility, and opacity properties
217
* @returns true if component is visible, false otherwise
218
*/
219
isVisible(): boolean;
220
```
221
222
**Usage Examples:**
223
224
```typescript
225
const wrapper = mount(MyComponent);
226
227
// Check visibility
228
expect(wrapper.isVisible()).toBe(true);
229
230
// After hiding with CSS
231
await wrapper.setData({ isHidden: true });
232
expect(wrapper.isVisible()).toBe(false);
233
```
234
235
## Inherited Methods from BaseWrapper
236
237
VueWrapper extends BaseWrapper and inherits all its methods for DOM querying and interaction:
238
239
```typescript { .api }
240
// Element querying
241
find<T extends Node = Node>(selector: string): DOMWrapper<T>;
242
findAll<T extends Node = Node>(selector: string): DOMWrapper<T>[];
243
findComponent(selector: FindComponentSelector): VueWrapper<any>;
244
findAllComponents(selector: FindAllComponentsSelector): VueWrapper<any>[];
245
246
// Element retrieval (throws if not found)
247
get<T extends Node = Node>(selector: string): DOMWrapper<T>;
248
getComponent(selector: FindComponentSelector): VueWrapper<any>;
249
250
// Content inspection
251
html(): string;
252
text(): string;
253
classes(): string[];
254
classes(className: string): boolean;
255
attributes(): Record<string, string>;
256
attributes(key: string): string;
257
258
// Event triggering
259
trigger(eventString: string, options?: TriggerOptions): Promise<void>;
260
```
261
262
## Type Safety Features
263
264
VueWrapper provides extensive TypeScript support:
265
266
```typescript { .api }
267
// Generic type preservation
268
const wrapper = mount<MyComponentType>(MyComponent);
269
wrapper.vm; // Typed as MyComponentType instance
270
271
// Component-specific prop typing
272
await wrapper.setProps({
273
validProp: "value" // TypeScript validates against component props
274
});
275
276
// Event payload typing
277
const events = wrapper.emitted<[string, number]>('custom-event');
278
// events is typed as [string, number][]
279
```
280
281
## Error Handling
282
283
VueWrapper methods may throw errors in these scenarios:
284
285
- **Component Not Found**: When using `getComponent()` with non-existent selector
286
- **Invalid Props**: When `setProps()` receives invalid prop types
287
- **Invalid Data**: When `setData()` receives data incompatible with component
288
- **Unmounted Component**: When calling methods on unmounted component
289
290
```typescript
291
const wrapper = mount(MyComponent);
292
293
try {
294
await wrapper.setProps({ invalidProp: "value" });
295
} catch (error) {
296
console.error("Props update failed:", error.message);
297
}
298
```