-
Notifications
You must be signed in to change notification settings - Fork 265
/
Copy pathvueWrapper.ts
306 lines (275 loc) · 9.87 KB
/
vueWrapper.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
import { nextTick, App, ComponentPublicInstance, VNode } from 'vue'
import { config } from './config'
import domEvents from './constants/dom-events'
import { VueElement, VueNode } from './types'
import { hasSetupState, mergeDeep } from './utils'
import { getRootNodes } from './utils/getRootNodes'
import { emitted, recordEvent, removeEventHistory } from './emit'
import BaseWrapper from './baseWrapper'
import type { DOMWrapper } from './domWrapper'
import {
createDOMWrapper,
registerFactory,
WrapperType
} from './wrapperFactory'
import { ShapeFlags } from './utils/vueShared'
/**
* Creates a proxy around the VM instance.
* This proxy returns the value from the setupState if there is one, or the one from the VM if not.
* See https://github.com/vuejs/core/issues/7103
*/
function createVMProxy<T extends ComponentPublicInstance>(
vm: T,
setupState: Record<string, any>,
exposed: Record<string, any> | null
): T {
return new Proxy(vm, {
get(vm, key, receiver) {
if (vm.$.exposed && vm.$.exposeProxy && key in vm.$.exposeProxy) {
// first if the key is exposed
return Reflect.get(vm.$.exposeProxy, key, receiver)
} else if (exposed && key in exposed) {
// first if the key is exposed
return Reflect.get(exposed, key, receiver)
} else if (key in setupState) {
// second if the key is acccessible from the setupState
return Reflect.get(setupState, key, receiver)
} else if (key in vm.$.appContext.config.globalProperties) {
// third if the key is a global property
return Reflect.get(
vm.$.appContext.config.globalProperties,
key,
receiver
)
} else {
// vm.$.ctx is the internal context of the vm
// with all variables, methods and props
return (vm as any).$.ctx[key]
}
},
set(vm, key, value, receiver) {
if (key in setupState) {
return Reflect.set(setupState, key, value, receiver)
} else {
return Reflect.set(vm, key, value, receiver)
}
},
has(vm, property) {
return Reflect.has(setupState, property) || Reflect.has(vm, property)
},
defineProperty(vm, key, attributes) {
if (key in setupState) {
return Reflect.defineProperty(setupState, key, attributes)
} else {
return Reflect.defineProperty(vm, key, attributes)
}
},
getOwnPropertyDescriptor(vm, property) {
if (property in setupState) {
return Reflect.getOwnPropertyDescriptor(setupState, property)
} else {
return Reflect.getOwnPropertyDescriptor(vm, property)
}
},
deleteProperty(vm, property) {
if (property in setupState) {
return Reflect.deleteProperty(setupState, property)
} else {
return Reflect.deleteProperty(vm, property)
}
}
})
}
export class VueWrapper<
VM = unknown,
T extends ComponentPublicInstance = VM & ComponentPublicInstance
> extends BaseWrapper<Node> {
private readonly componentVM: T
private readonly rootVM: ComponentPublicInstance | undefined | null
private readonly __app: App | null
private readonly __setProps:
| ((props: Record<string, unknown>) => void)
| undefined
private cleanUpCallbacks: Array<() => void> = []
constructor(
app: App | null,
vm: T,
setProps?: (props: Record<string, unknown>) => void
) {
super(vm?.$el)
this.__app = app
// root is null on functional components
this.rootVM = vm?.$root
// `vm.$.setupState` is what the template has access to
// so even if the component is closed (as they are by default for `script setup`)
// a test will still be able to do something like
// `expect(wrapper.vm.count).toBe(1)`
// if we return it as `vm`
// This does not work for functional components though (as they have no vm)
// or for components with a setup that returns a render function (as they have an empty proxy)
// in both cases, we return `vm` directly instead.
//
// NOTE https://github.com/vuejs/test-utils/issues/2591
// I'm sry i'm not entirely sure why, but exposed properties — via expose/defineExpose
// are not assigned to the componentVM when the the `vm` argument provided
// to this constructor comes from `findComponent` — as in, not the original instance
// but already the proxied one. I first suspected that was by design of defineExpose
// but that doesn't explain why it works when finding a .vue component or
// vs it's bundled version, where the different is conversion of to a render
// function. Also i've noticed that sometimes we can get some exceptions in
// bundle code becuase render function is hoisted and exposed if properties
// are returned to template, they also become available in th einstance.
//
if (hasSetupState(vm)) {
this.componentVM = createVMProxy<T>(vm, vm.$.setupState, vm.$.exposed)
} else {
this.componentVM = vm
Object.assign(this.componentVM, vm.$.exposed)
}
this.__setProps = setProps
this.attachNativeEventListener()
config.plugins.VueWrapper.extend(this)
}
private get hasMultipleRoots(): boolean {
// Recursive check subtree for nested root elements
// <template>
// <WithMultipleRoots />
// </template>
const checkTree = (subTree: VNode): boolean => {
// if the subtree is an array of children, we have multiple root nodes
if (subTree.shapeFlag === ShapeFlags.ARRAY_CHILDREN) return true
if (
subTree.shapeFlag & ShapeFlags.STATEFUL_COMPONENT ||
subTree.shapeFlag & ShapeFlags.FUNCTIONAL_COMPONENT
) {
// We are rendering other component, check it's tree instead
if (subTree.component?.subTree) {
return checkTree(subTree.component.subTree)
}
// Component has multiple children
if (subTree.shapeFlag & ShapeFlags.ARRAY_CHILDREN) {
return true
}
}
return false
}
return checkTree(this.vm.$.subTree)
}
protected getRootNodes(): VueNode[] {
return getRootNodes(this.vm.$.vnode)
}
private get parentElement(): VueElement {
return this.vm.$el.parentElement
}
getCurrentComponent() {
return this.vm.$
}
exists() {
return !this.getCurrentComponent().isUnmounted
}
findAll<K extends keyof HTMLElementTagNameMap>(
selector: K
): DOMWrapper<HTMLElementTagNameMap[K]>[]
findAll<K extends keyof SVGElementTagNameMap>(
selector: K
): DOMWrapper<SVGElementTagNameMap[K]>[]
findAll<T extends Element>(selector: string): DOMWrapper<T>[]
findAll(selector: string): DOMWrapper<Element>[] {
return this.findAllDOMElements(selector).map(createDOMWrapper)
}
private attachNativeEventListener(): void {
const vm = this.vm
if (!vm) return
const emits = vm.$options.emits
? // if emits is declared as an array
Array.isArray(vm.$options.emits)
? // use it
vm.$options.emits
: // otherwise it's declared as an object
// and we only need the keys
Object.keys(vm.$options.emits)
: []
const elementRoots = this.getRootNodes().filter(
(node): node is Element => node instanceof Element
)
if (elementRoots.length !== 1) {
return
}
const [element] = elementRoots
for (const eventName of Object.keys(domEvents)) {
// if a component includes events in 'emits' with the same name as native
// events, the native events with that name should be ignored
// @see https://github.com/vuejs/rfcs/blob/master/active-rfcs/0030-emits-option.md#fallthrough-control
if (emits.includes(eventName)) continue
const eventListener: EventListener = (...args) => {
recordEvent(vm.$, eventName, args)
}
element.addEventListener(eventName, eventListener)
this.cleanUpCallbacks.push(() => {
element.removeEventListener(eventName, eventListener)
})
}
}
get element(): T['$el'] {
// if the component has multiple root elements, we use the parent's element
return this.hasMultipleRoots ? this.parentElement : this.vm.$el
}
get vm(): T {
return this.componentVM
}
props(): T['$props']
props<Selector extends keyof T['$props']>(
selector: Selector
): T['$props'][Selector]
props<Selector extends keyof T['$props']>(
selector?: Selector
): T['$props'] | T['$props'][Selector] {
const props = this.componentVM.$props as T['$props']
return selector ? props[selector] : props
}
emitted<T = unknown>(): Record<string, T[]>
emitted<T = unknown[]>(eventName: string): undefined | T[]
emitted<T = unknown>(
eventName?: string
): undefined | T[] | Record<string, T[]> {
return emitted(this.vm, eventName)
}
isVisible(): boolean {
const domWrapper = createDOMWrapper(this.element)
return domWrapper.isVisible()
}
setData(data: Record<string, unknown>): Promise<void> {
mergeDeep(this.componentVM.$data, data)
return nextTick()
}
setProps(props: Partial<T['$props']>): Promise<void> {
// if this VM's parent is not the root or if setProps does not exist, error out
if (this.vm.$parent !== this.rootVM || !this.__setProps) {
throw Error('You can only use setProps on your mounted component')
}
this.__setProps(props)
return nextTick()
}
setValue(value: unknown, prop?: string): Promise<void> {
const propEvent = prop || 'modelValue'
this.vm.$emit(`update:${propEvent}`, value)
return this.vm.$nextTick()
}
unmount() {
// preventing dispose of child component
if (!this.__app) {
throw new Error(
`wrapper.unmount() can only be called by the root wrapper`
)
}
// Clear emitted events cache for this component instance
removeEventHistory(this.vm)
this.cleanUpCallbacks.forEach((cb) => cb())
this.cleanUpCallbacks = []
this.__app.unmount()
}
}
registerFactory(
WrapperType.VueWrapper,
(app, vm, setProps) => new VueWrapper(app, vm, setProps)
)