forked from vuejs/test-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathemit.ts
71 lines (58 loc) · 1.64 KB
/
emit.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
import {
setDevtoolsHook,
devtools,
ComponentPublicInstance,
ComponentInternalInstance
} from 'vue'
type Events<T = unknown> = Record<number, Record<string, T[]>>
const enum DevtoolsHooks {
COMPONENT_EMIT = 'component:emit'
}
let events: Events = {}
export function emitted<T = unknown>(
vm: ComponentPublicInstance,
eventName?: string
): undefined | T[] | Record<string, T[]> {
const cid = vm.$.uid
const vmEvents: Record<string, T[]> = (events as Events<T>)[cid] || {}
if (eventName) {
return vmEvents ? vmEvents[eventName] : undefined
}
return vmEvents
}
export const attachEmitListener = () => {
// use devtools to capture this "emit"
setDevtoolsHook(createDevTools(), {})
}
// devtools hook only catches Vue component custom events
function createDevTools(): any {
return {
emit(eventType, ...payload) {
if (eventType !== DevtoolsHooks.COMPONENT_EMIT) return
const [_, componentVM, event, eventArgs] = payload
recordEvent(componentVM, event, eventArgs)
}
} as Partial<typeof devtools>
}
export const recordEvent = (
vm: ComponentInternalInstance,
event: string,
args: unknown[]
): void => {
// Functional component wrapper creates a parent component
let wrapperVm = vm
while (typeof wrapperVm?.type === 'function') wrapperVm = wrapperVm.parent!
const cid = wrapperVm.uid
if (!(cid in events)) {
events[cid] = {}
}
if (!(event in events[cid])) {
events[cid][event] = []
}
// Record the event message sent by the emit
events[cid][event].push(args)
}
export const removeEventHistory = (vm: ComponentPublicInstance): void => {
const cid = vm.$.uid
delete events[cid]
}