-
Notifications
You must be signed in to change notification settings - Fork 667
/
Copy pathwrapper.js
525 lines (458 loc) · 15.2 KB
/
wrapper.js
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
// @flow
import Vue from 'vue'
import getSelectorTypeOrThrow from '../lib/get-selector-type'
import {
REF_SELECTOR,
COMPONENT_SELECTOR,
NAME_SELECTOR
} from '../lib/consts'
import {
vmCtorMatchesName,
vmCtorMatchesSelector,
vmFunctionalCtorMatchesSelector
} from '../lib/find-vue-components'
import VueWrapper from './vue-wrapper'
import WrapperArray from './wrapper-array'
import ErrorWrapper from './error-wrapper'
import { throwError, warn } from '../lib/util'
import findAll from '../lib/find'
import createWrapper from './create-wrapper'
export default class Wrapper implements BaseWrapper {
vnode: VNode;
vm: Component | null;
_emitted: { [name: string]: Array<Array<any>> };
_emittedByOrder: Array<{ name: string; args: Array<any> }>;
isVueComponent: boolean;
element: HTMLElement;
update: Function;
options: WrapperOptions;
version: number
constructor (vnode: VNode, update: Function, options: WrapperOptions) {
this.vnode = vnode
this.element = vnode.elm
this.update = update
this.options = options
this.version = Number(`${Vue.version.split('.')[0]}.${Vue.version.split('.')[1]}`)
}
at () {
throwError('at() must be called on a WrapperArray')
}
/**
* Returns an Object containing all the attribute/value pairs on the element.
*/
attributes (): { [name: string]: string } {
const attributes = this.element.attributes
const attributeMap = {}
for (let i = 0; i < attributes.length; i++) {
const att = attributes.item(i)
attributeMap[att.localName] = att.value
}
return attributeMap
}
/**
* Returns an Array containing all the classes on the element
*/
classes (): Array<string> {
let classes = this.element.className ? this.element.className.split(' ') : []
// Handle converting cssmodules identifiers back to the original class name
if (this.vm && this.vm.$style) {
const cssModuleIdentifiers = {}
let moduleIdent
Object.keys(this.vm.$style).forEach((key) => {
// $FlowIgnore : Flow thinks vm is a property
moduleIdent = this.vm.$style[key]
// CSS Modules may be multi-class if they extend others.
// Extended classes should be already present in $style.
moduleIdent = moduleIdent.split(' ')[0]
cssModuleIdentifiers[moduleIdent] = key
})
classes = classes.map(className => cssModuleIdentifiers[className] || className)
}
return classes
}
/**
* Checks if wrapper contains provided selector.
*/
contains (selector: Selector) {
const selectorType = getSelectorTypeOrThrow(selector, 'contains')
const nodes = findAll(this.vm, this.vnode, selectorType, selector)
const is = selectorType === REF_SELECTOR ? false : this.is(selector)
return nodes.length > 0 || is
}
/**
* Returns an object containing custom events emitted by the Wrapper vm
*/
emitted (event?: string) {
if (!this._emitted && !this.vm) {
throwError('wrapper.emitted() can only be called on a Vue instance')
}
if (event) {
return this._emitted[event]
}
return this._emitted
}
/**
* Returns an Array containing custom events emitted by the Wrapper vm
*/
emittedByOrder () {
if (!this._emittedByOrder && !this.vm) {
throwError('wrapper.emittedByOrder() can only be called on a Vue instance')
}
return this._emittedByOrder
}
/**
* Utility to check wrapper exists. Returns true as Wrapper always exists
*/
exists (): boolean {
if (this.vm) {
return !!this.vm && !this.vm._isDestroyed
}
return true
}
/**
* Checks if wrapper has an attribute with matching value
*/
hasAttribute (attribute: string, value: string) {
warn('hasAttribute() has been deprecated and will be removed in version 1.0.0. Use attributes() instead—https://vue-test-utils.vuejs.org/en/api/wrapper/attributes')
if (typeof attribute !== 'string') {
throwError('wrapper.hasAttribute() must be passed attribute as a string')
}
if (typeof value !== 'string') {
throwError('wrapper.hasAttribute() must be passed value as a string')
}
return !!(this.element && this.element.getAttribute(attribute) === value)
}
/**
* Asserts wrapper has a class name
*/
hasClass (className: string) {
warn('hasClass() has been deprecated and will be removed in version 1.0.0. Use classes() instead—https://vue-test-utils.vuejs.org/en/api/wrapper/classes')
let targetClass = className
if (typeof targetClass !== 'string') {
throwError('wrapper.hasClass() must be passed a string')
}
// if $style is available and has a matching target, use that instead.
if (this.vm && this.vm.$style && this.vm.$style[targetClass]) {
targetClass = this.vm.$style[targetClass]
}
const containsAllClasses = targetClass
.split(' ')
.every(target => this.element.classList.contains(target))
return !!(this.element && containsAllClasses)
}
/**
* Asserts wrapper has a prop name
*/
hasProp (prop: string, value: string) {
warn('hasProp() has been deprecated and will be removed in version 1.0.0. Use props() instead—https://vue-test-utils.vuejs.org/en/api/wrapper/props')
if (!this.isVueComponent) {
throwError('wrapper.hasProp() must be called on a Vue instance')
}
if (typeof prop !== 'string') {
throwError('wrapper.hasProp() must be passed prop as a string')
}
// $props object does not exist in Vue 2.1.x, so use $options.propsData instead
if (this.vm && this.vm.$options && this.vm.$options.propsData && this.vm.$options.propsData[prop] === value) {
return true
}
return !!this.vm && !!this.vm.$props && this.vm.$props[prop] === value
}
/**
* Checks if wrapper has a style with value
*/
hasStyle (style: string, value: string) {
if (typeof style !== 'string') {
throwError('wrapper.hasStyle() must be passed style as a string')
}
if (typeof value !== 'string') {
throwError('wrapper.hasClass() must be passed value as string')
}
/* istanbul ignore next */
if (navigator.userAgent.includes && (navigator.userAgent.includes('node.js') || navigator.userAgent.includes('jsdom'))) {
console.warn('wrapper.hasStyle is not fully supported when running jsdom - only inline styles are supported') // eslint-disable-line no-console
}
const body = document.querySelector('body')
const mockElement = document.createElement('div')
if (!(body instanceof HTMLElement)) {
return false
}
const mockNode = body.insertBefore(mockElement, null)
// $FlowIgnore : Flow thinks style[style] returns a number
mockElement.style[style] = value
if (!this.options.attachedToDocument) {
const vm = this.vm || this.vnode.context.$root
body.insertBefore(vm.$root._vnode.elm, null)
}
const elStyle = window.getComputedStyle(this.element)[style]
const mockNodeStyle = window.getComputedStyle(mockNode)[style]
return !!(elStyle && mockNodeStyle && elStyle === mockNodeStyle)
}
/**
* Finds first node in tree of the current wrapper that matches the provided selector.
*/
find (selector: Selector): Wrapper | ErrorWrapper | VueWrapper {
const selectorType = getSelectorTypeOrThrow(selector, 'find')
const nodes = findAll(this.vm, this.vnode, selectorType, selector)
if (nodes.length === 0) {
if (selector.ref) {
return new ErrorWrapper(`ref="${selector.ref}"`)
}
return new ErrorWrapper(typeof selector === 'string' ? selector : 'Component')
}
return createWrapper(nodes[0], this.update, this.options)
}
/**
* Finds node in tree of the current wrapper that matches the provided selector.
*/
findAll (selector: Selector): WrapperArray {
const selectorType = getSelectorTypeOrThrow(selector, 'findAll')
const nodes = findAll(this.vm, this.vnode, selectorType, selector)
const wrappers = nodes.map(node =>
createWrapper(node, this.update, this.options)
)
return new WrapperArray(wrappers)
}
/**
* Returns HTML of element as a string
*/
html (): string {
return this.element.outerHTML
}
/**
* Checks if node matches selector
*/
is (selector: Selector): boolean {
const selectorType = getSelectorTypeOrThrow(selector, 'is')
if (selectorType === NAME_SELECTOR) {
if (!this.vm) {
return false
}
return vmCtorMatchesName(this.vm, selector.name)
}
if (selectorType === COMPONENT_SELECTOR) {
if (!this.vm) {
return false
}
if (selector.functional) {
return vmFunctionalCtorMatchesSelector(this.vm._vnode, selector._Ctor)
}
return vmCtorMatchesSelector(this.vm, selector)
}
if (selectorType === REF_SELECTOR) {
throwError('$ref selectors can not be used with wrapper.is()')
}
if (typeof selector === 'object') {
return false
}
return !!(this.element &&
this.element.getAttribute &&
this.element.matches(selector))
}
/**
* Checks if node is empty
*/
isEmpty (): boolean {
return this.vnode.children === undefined || this.vnode.children.length === 0
}
/**
* Checks if wrapper is a vue instance
*/
isVueInstance (): boolean {
return !!this.isVueComponent
}
/**
* Returns name of component, or tag name if node is not a Vue component
*/
name (): string {
if (this.vm) {
return this.vm.$options.name
}
return this.vnode.tag
}
/**
* Returns an Object containing the prop name/value pairs on the element
*/
props (): { [name: string]: any } {
if (!this.vm) {
throwError('wrapper.props() must be called on a Vue instance')
}
// $props object does not exist in Vue 2.1.x, so use $options.propsData instead
let _props
if (this.vm && this.vm.$options && this.vm.$options.propsData) {
_props = this.vm.$options.propsData
} else {
// $FlowIgnore
_props = this.vm.$props
}
return _props || {} // Return an empty object if no props exist
}
/**
* Sets vm data
*/
setData (data: Object) {
if (!this.vm) {
throwError('wrapper.setData() can only be called on a Vue instance')
}
Object.keys(data).forEach((key) => {
// $FlowIgnore : Problem with possibly null this.vm
this.vm.$set(this.vm, [key], data[key])
})
this.update()
}
/**
* Sets vm computed
*/
setComputed (computed: Object) {
if (!this.isVueComponent) {
throwError('wrapper.setComputed() can only be called on a Vue instance')
}
Object.keys(computed).forEach((key) => {
if (this.version > 2.1) {
// $FlowIgnore : Problem with possibly null this.vm
if (!this.vm._computedWatchers[key]) {
throwError(`wrapper.setComputed() was passed a value that does not exist as a computed property on the Vue instance. Property ${key} does not exist on the Vue instance`)
}
// $FlowIgnore : Problem with possibly null this.vm
this.vm._computedWatchers[key].value = computed[key]
// $FlowIgnore : Problem with possibly null this.vm
this.vm._computedWatchers[key].getter = () => computed[key]
} else {
let isStore = false
// $FlowIgnore : Problem with possibly null this.vm
this.vm._watchers.forEach(watcher => {
if (watcher.getter.vuex && key in watcher.vm.$options.store.getters) {
watcher.vm.$options.store.getters = {
...watcher.vm.$options.store.getters
}
Object.defineProperty(watcher.vm.$options.store.getters, key, { get: function () { return computed[key] } })
isStore = true
}
})
// $FlowIgnore : Problem with possibly null this.vm
if (!isStore && !this.vm._watchers.some(w => w.getter.name === key)) {
throwError(`wrapper.setComputed() was passed a value that does not exist as a computed property on the Vue instance. Property ${key} does not exist on the Vue instance`)
}
// $FlowIgnore : Problem with possibly null this.vm
this.vm._watchers.forEach((watcher) => {
if (watcher.getter.name === key) {
watcher.value = computed[key]
watcher.getter = () => computed[key]
}
})
}
})
this.update()
}
/**
* Sets vm methods
*/
setMethods (methods: Object) {
if (!this.isVueComponent) {
throwError('wrapper.setMethods() can only be called on a Vue instance')
}
Object.keys(methods).forEach((key) => {
// $FlowIgnore : Problem with possibly null this.vm
this.vm[key] = methods[key]
// $FlowIgnore : Problem with possibly null this.vm
this.vm.$options.methods[key] = methods[key]
})
this.update()
}
/**
* Sets vm props
*/
setProps (data: Object) {
if (!this.isVueComponent || !this.vm) {
throwError('wrapper.setProps() can only be called on a Vue instance')
}
Object.keys(data).forEach((key) => {
// $FlowIgnore : Problem with possibly null this.vm
if (this.vm._props) {
this.vm._props[key] = data[key]
} else {
// $FlowIgnore : Problem with possibly null this.vm
this.vm[key] = data[key]
}
})
this.update()
// $FlowIgnore : Problem with possibly null this.vm
this.vnode = this.vm._vnode
}
/**
* Return text of wrapper element
*/
text (): string {
if (!this.element) {
throwError('cannot call wrapper.text() on a wrapper without an element')
}
return this.element.textContent.trim()
}
/**
* Calls destroy on vm
*/
destroy () {
if (!this.isVueComponent) {
throwError('wrapper.destroy() can only be called on a Vue instance')
}
if (this.element.parentNode) {
this.element.parentNode.removeChild(this.element)
}
// $FlowIgnore
this.vm.$destroy()
}
/**
* Dispatches a DOM event on wrapper
*/
trigger (type: string, options: Object = {}) {
if (typeof type !== 'string') {
throwError('wrapper.trigger() must be passed a string')
}
if (!this.element) {
throwError('cannot call wrapper.trigger() on a wrapper without an element')
}
if (options.target) {
throwError('you cannot set the target value of an event. See the notes section of the docs for more details—https://vue-test-utils.vuejs.org/en/api/wrapper/trigger.html')
}
const modifiers = {
enter: 13,
tab: 9,
delete: 46,
esc: 27,
space: 32,
up: 38,
down: 40,
left: 37,
right: 39,
end: 35,
home: 36,
backspace: 8,
insert: 45,
pageup: 33,
pagedown: 34
}
const event = type.split('.')
let eventObject
// Fallback for IE10,11 - https://stackoverflow.com/questions/26596123
if (typeof (window.Event) === 'function') {
eventObject = new window.Event(event[0], {
bubbles: true,
cancelable: true
})
} else {
eventObject = document.createEvent('Event')
eventObject.initEvent(event[0], true, true)
}
if (options) {
Object.keys(options).forEach(key => {
// $FlowIgnore
eventObject[key] = options[key]
})
}
if (event.length === 2) {
// $FlowIgnore
eventObject.keyCode = modifiers[event[1]]
}
this.element.dispatchEvent(eventObject)
this.update()
}
}