forked from vuejs/vue-test-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwrapper.js
587 lines (524 loc) · 15.4 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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
// @flow
import Vue from 'vue'
import pretty from 'pretty'
import getSelector from './get-selector'
import { REF_SELECTOR, FUNCTIONAL_OPTIONS, VUE_VERSION } from 'shared/consts'
import config from './config'
import WrapperArray from './wrapper-array'
import ErrorWrapper from './error-wrapper'
import { throwError, getCheckedEvent, isPhantomJS } from 'shared/util'
import find from './find'
import createWrapper from './create-wrapper'
import { recursivelySetData } from './recursively-set-data'
import { matches } from './matches'
import createDOMEvent from './create-dom-event'
import { throwIfInstancesThrew } from './error'
export default class Wrapper implements BaseWrapper {
+vnode: VNode | null
+vm: Component | void
_emitted: { [name: string]: Array<Array<any>> }
_emittedByOrder: Array<{ name: string, args: Array<any> }>
+element: Element
+options: WrapperOptions
isFunctionalComponent: boolean
rootNode: VNode | Element
constructor(
node: VNode | Element,
options: WrapperOptions,
isVueWrapper?: boolean
) {
const vnode = node instanceof Element ? null : node
const element = node instanceof Element ? node : node.elm
// Prevent redefine by VueWrapper
if (!isVueWrapper) {
// $FlowIgnore : issue with defineProperty
Object.defineProperty(this, 'rootNode', {
get: () => vnode || element,
set: () => throwError('wrapper.rootNode is read-only')
})
// $FlowIgnore
Object.defineProperty(this, 'vnode', {
get: () => vnode,
set: () => throwError('wrapper.vnode is read-only')
})
// $FlowIgnore
Object.defineProperty(this, 'element', {
get: () => element,
set: () => throwError('wrapper.element is read-only')
})
// $FlowIgnore
Object.defineProperty(this, 'vm', {
get: () => undefined,
set: () => throwError('wrapper.vm is read-only')
})
}
const frozenOptions = Object.freeze(options)
// $FlowIgnore
Object.defineProperty(this, 'options', {
get: () => frozenOptions,
set: () => throwError('wrapper.options is read-only')
})
if (
this.vnode &&
(this.vnode[FUNCTIONAL_OPTIONS] || this.vnode.functionalContext)
) {
this.isFunctionalComponent = true
}
}
at(): void {
throwError('at() must be called on a WrapperArray')
}
/**
* Returns an Object containing all the attribute/value pairs on the element.
*/
attributes(key?: string): { [name: string]: 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 key ? attributeMap[key] : attributeMap
}
/**
* Returns an Array containing all the classes on the element
*/
classes(className?: string): Array<string> | boolean {
const classAttribute = this.element.getAttribute('class')
let classes = classAttribute ? classAttribute.split(' ') : []
// Handle converting cssmodules identifiers back to the original class name
if (this.vm && this.vm.$style) {
const cssModuleIdentifiers = Object.keys(this.vm.$style).reduce(
(acc, key) => {
// $FlowIgnore
const moduleIdent = this.vm.$style[key]
if (moduleIdent) {
acc[moduleIdent.split(' ')[0]] = key
}
return acc
},
{}
)
classes = classes.map(name => cssModuleIdentifiers[name] || name)
}
return className ? !!(classes.indexOf(className) > -1) : classes
}
/**
* Checks if wrapper contains provided selector.
*/
contains(rawSelector: Selector): boolean {
const selector = getSelector(rawSelector, 'contains')
const nodes = find(this.rootNode, this.vm, selector)
return nodes.length > 0
}
/**
* Calls destroy on vm
*/
destroy(): void {
if (!this.isVueInstance() && !this.isFunctionalComponent) {
throwError(
`wrapper.destroy() can only be called on a Vue instance or ` +
`functional component.`
)
}
if (this.element.parentNode) {
this.element.parentNode.removeChild(this.element)
}
if (this.isVueInstance()) {
// $FlowIgnore
this.vm.$destroy()
throwIfInstancesThrew(this.vm)
}
}
/**
* Returns an object containing custom events emitted by the Wrapper vm
*/
emitted(
event?: string
): Array<Array<any>> | { [name: string]: Array<Array<any>> } {
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(): Array<{ name: string, args: Array<any> }> {
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
}
filter() {
throwError('filter() must be called on a WrapperArray')
}
/**
* Finds first node in tree of the current wrapper that
* matches the provided selector.
*/
find(rawSelector: Selector): Wrapper | ErrorWrapper {
const selector = getSelector(rawSelector, 'find')
const node = find(this.rootNode, this.vm, selector)[0]
if (!node) {
if (selector.type === REF_SELECTOR) {
return new ErrorWrapper(`ref="${selector.value.ref}"`)
}
return new ErrorWrapper(
typeof selector.value === 'string' ? selector.value : 'Component'
)
}
return createWrapper(node, this.options)
}
/**
* Finds node in tree of the current wrapper that matches
* the provided selector.
*/
findAll(rawSelector: Selector): WrapperArray {
const selector = getSelector(rawSelector, 'findAll')
const nodes = find(this.rootNode, this.vm, selector)
const wrappers = nodes.map(node => {
// Using CSS Selector, returns a VueWrapper instance if the root element
// binds a Vue instance.
return createWrapper(node, this.options)
})
return new WrapperArray(wrappers)
}
/**
* Returns HTML of element as a string
*/
html(options?: HtmlOptions): string {
if (options && !options.prettyPrint) {
return this.element.outerHTML
}
return pretty(this.element.outerHTML)
}
/**
* Checks if node matches selector
*/
is(rawSelector: Selector): boolean {
const selector = getSelector(rawSelector, 'is')
if (selector.type === REF_SELECTOR) {
throwError('$ref selectors can not be used with wrapper.is()')
}
return matches(this.rootNode, selector)
}
/**
* Checks if node is empty
*/
isEmpty(): boolean {
if (!this.vnode) {
return this.element.innerHTML === ''
}
const nodes = []
let node = this.vnode
let i = 0
while (node) {
if (node.child) {
nodes.push(node.child._vnode)
}
node.children &&
node.children.forEach(n => {
nodes.push(n)
})
node = nodes[i++]
}
return nodes.every(n => n.isComment || n.child)
}
/**
* Checks if node is visible
*/
isVisible(): boolean {
let element = this.element
while (element) {
if (
element.style &&
(element.style.visibility === 'hidden' ||
element.style.display === 'none')
) {
return false
}
element = element.parentElement
}
return true
}
/**
* Checks if wrapper is a vue instance
*/
isVueInstance(): boolean {
return !!this.vm
}
/**
* Returns name of component, or tag name if node is not a Vue component
*/
name(): string {
if (this.vm) {
return (
this.vm.$options.name ||
// compat for Vue < 2.3
(this.vm.$options.extendOptions && this.vm.$options.extendOptions.name)
)
}
if (!this.vnode) {
return this.element.tagName
}
return this.vnode.tag
}
/**
* Returns an Object containing the prop name/value pairs on the element
*/
props(key?: string): { [name: string]: any } | any {
if (this.isFunctionalComponent) {
throwError(
`wrapper.props() cannot be called on a mounted functional component.`
)
}
if (!this.vm) {
throwError('wrapper.props() must be called on a Vue instance')
}
const props = {}
const keys = this.vm && this.vm.$options._propKeys
if (keys) {
;(keys || {}).forEach(key => {
if (this.vm) {
props[key] = this.vm[key]
}
})
}
if (key) {
return props[key]
}
return props
}
/**
* Checks radio button or checkbox element
*/
setChecked(checked: boolean = true): void {
if (typeof checked !== 'boolean') {
throwError('wrapper.setChecked() must be passed a boolean')
}
const tagName = this.element.tagName
// $FlowIgnore
const type = this.attributes().type
const event = getCheckedEvent()
if (tagName === 'INPUT' && type === 'checkbox') {
if (this.element.checked === checked) {
return
}
if (event !== 'click' || isPhantomJS) {
// $FlowIgnore
this.element.checked = checked
}
this.trigger(event)
return
}
if (tagName === 'INPUT' && type === 'radio') {
if (!checked) {
throwError(
`wrapper.setChecked() cannot be called with parameter false on a ` +
`<input type="radio" /> element.`
)
}
if (event !== 'click' || isPhantomJS) {
// $FlowIgnore
this.element.selected = true
}
this.trigger(event)
return
}
throwError(`wrapper.setChecked() cannot be called on this element`)
}
/**
* Selects <option></option> element
*/
setSelected(): void {
const tagName = this.element.tagName
if (tagName === 'SELECT') {
throwError(
`wrapper.setSelected() cannot be called on select. Call it on one of ` +
`its options`
)
}
if (tagName === 'OPTION') {
// $FlowIgnore
this.element.selected = true
// $FlowIgnore
let parentElement = this.element.parentElement
// $FlowIgnore
if (parentElement.tagName === 'OPTGROUP') {
// $FlowIgnore
parentElement = parentElement.parentElement
}
// $FlowIgnore
createWrapper(parentElement, this.options).trigger('change')
return
}
throwError(`wrapper.setSelected() cannot be called on this element`)
}
/**
* Sets vm data
*/
setData(data: Object): void {
if (this.isFunctionalComponent) {
throwError(`wrapper.setData() cannot be called on a functional component`)
}
if (!this.vm) {
throwError(`wrapper.setData() can only be called on a Vue instance`)
}
recursivelySetData(this.vm, this.vm, data)
}
/**
* Sets vm methods
*/
setMethods(methods: Object): void {
if (!this.isVueInstance()) {
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]
})
if (this.vnode) {
const context = this.vnode.context
if (context.$options.render) context._update(context._render())
}
}
/**
* Sets vm props
*/
setProps(data: Object): void {
const originalConfig = Vue.config.silent
Vue.config.silent = config.silent
if (this.isFunctionalComponent) {
throwError(
`wrapper.setProps() cannot be called on a functional component`
)
}
if (!this.vm) {
throwError(`wrapper.setProps() can only be called on a Vue instance`)
}
Object.keys(data).forEach(key => {
if (
typeof data[key] === 'object' &&
data[key] !== null &&
// $FlowIgnore : Problem with possibly null this.vm
data[key] === this.vm[key]
) {
throwError(
`wrapper.setProps() called with the same object of the existing ` +
`${key} property. You must call wrapper.setProps() with a new ` +
`object to trigger reactivity`
)
}
if (
!this.vm ||
!this.vm.$options._propKeys ||
!this.vm.$options._propKeys.some(prop => prop === key)
) {
if (VUE_VERSION > 2.3) {
// $FlowIgnore : Problem with possibly null this.vm
this.vm.$attrs[key] = data[key]
return
}
throwError(
`wrapper.setProps() called with ${key} property which ` +
`is not defined on the component`
)
}
if (this.vm && this.vm._props) {
// Set actual props value
this.vm._props[key] = data[key]
// $FlowIgnore : Problem with possibly null this.vm
this.vm[key] = data[key]
} else {
// $FlowIgnore : Problem with possibly null this.vm.$options
this.vm.$options.propsData[key] = data[key]
// $FlowIgnore : Problem with possibly null this.vm
this.vm[key] = data[key]
// $FlowIgnore : Need to call this twice to fix watcher bug in 2.0.x
this.vm[key] = data[key]
}
})
// $FlowIgnore : Problem with possibly null this.vm
this.vm.$forceUpdate()
Vue.config.silent = originalConfig
}
/**
* Sets element value and triggers input event
*/
setValue(value: any): void {
const tagName = this.element.tagName
// $FlowIgnore
const type = this.attributes().type
if (tagName === 'OPTION') {
throwError(
`wrapper.setValue() cannot be called on an <option> element. Use ` +
`wrapper.setSelected() instead`
)
} else if (tagName === 'INPUT' && type === 'checkbox') {
throwError(
`wrapper.setValue() cannot be called on a <input type="checkbox" /> ` +
`element. Use wrapper.setChecked() instead`
)
} else if (tagName === 'INPUT' && type === 'radio') {
throwError(
`wrapper.setValue() cannot be called on a <input type="radio" /> ` +
`element. Use wrapper.setChecked() instead`
)
} else if (
tagName === 'INPUT' ||
tagName === 'TEXTAREA' ||
tagName === 'SELECT'
) {
const event = tagName === 'SELECT' ? 'change' : 'input'
// $FlowIgnore
this.element.value = value
this.trigger(event)
} else {
throwError(`wrapper.setValue() cannot be called on this element`)
}
}
/**
* Return text of wrapper element
*/
text(): string {
return this.element.textContent.trim()
}
/**
* Dispatches a DOM event on wrapper
*/
trigger(type: string, options: Object = {}) {
if (typeof type !== 'string') {
throwError('wrapper.trigger() must be passed a string')
}
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/api/wrapper/trigger.html`
)
}
// Don't fire event on a disabled element
if (this.attributes().disabled) {
return
}
const event = createDOMEvent(type, options)
this.element.dispatchEvent(event)
}
}