-
Notifications
You must be signed in to change notification settings - Fork 258
/
vueWrapper.ts
224 lines (195 loc) · 6.73 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
import {
nextTick,
App,
ComponentCustomProperties,
ComponentPublicInstance
} from 'vue'
// @ts-ignore todo - No DefinitelyTyped package exists for this
import pretty from 'pretty'
import { config } from './config'
import domEvents from './constants/dom-events'
import { VueElement, VueNode } from './types'
import { 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 { VNode } from '@vue/runtime-core'
import { ShapeFlags } from './utils/vueShared'
export class VueWrapper<
T extends Omit<
ComponentPublicInstance,
'$emit' | keyof ComponentCustomProperties
> & {
$emit: (event: any, ...args: any[]) => void
} & ComponentCustomProperties = ComponentPublicInstance
> extends BaseWrapper<Node> {
private componentVM: T
private rootVM: ComponentPublicInstance | undefined | null
private __app: App | null
private __setProps: ((props: Record<string, unknown>) => void) | undefined
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.$.proxy` 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
this.componentVM =
vm &&
// a component with a setup that returns a render function will have no `devtoolsRawSetupState`
(vm.$ as unknown as { devtoolsRawSetupState: any }).devtoolsRawSetupState
? ((vm.$ as any).proxy as T)
: (vm as T)
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 (let 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
element.addEventListener(eventName, (...args) => {
recordEvent(vm.$, eventName, args)
})
}
}
get element(): Element {
// 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(): { [key: string]: any }
props(selector: string): any
props(selector?: string): { [key: string]: any } | any {
const props = this.componentVM.$props as { [key: string]: any }
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: Record<string, unknown>): 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.__app.unmount()
}
}
registerFactory(
WrapperType.VueWrapper,
(app, vm, setProps) => new VueWrapper(app, vm, setProps)
)