-
Notifications
You must be signed in to change notification settings - Fork 1
/
events.test.ts
114 lines (90 loc) · 2.34 KB
/
events.test.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
/**
* 测试用例
*/
import Events from './events'
// 发送与接收
it('Send and receive', () => {
let dummy = 0
Events.miao.on(val => dummy = val)
Events.miao.emit(1)
expect(dummy).toBe(1)
})
// 移除事件监听
it('Delete event on', () => {
let dummy1 = 0, dummy2 = 0, dummy3
const func = (val: number) => dummy1 = val
Events.miao.on(func)
Events.miao.on(val => dummy2 = val)
Events.wang.on(val => dummy3 = val)
Events.miao.off(func)
Events.miao.emit(1)
expect(dummy1).toBe(0)
expect(dummy2).toBe(1)
Events.wang.emit('233', 0)
expect(dummy3).toBe('233')
})
// 移除该事件的全部监听
it('Delete all event on', () => {
let dummy1 = 0, dummy2 = 0, dummy3
const func = (val: number) => dummy1 = val
Events.miao.on(func)
Events.miao.on(val => dummy2 = val)
Events.wang.on(val => dummy3 = val)
Events.miao.offAll()
Events.miao.emit(1)
expect(dummy1).toBe(0)
expect(dummy2).toBe(0)
Events.wang.emit('233', 0)
expect(dummy3).toBe('233')
})
// 一次性事件监听
it('Event once', () => {
let dummy = 0
Events.updated.once(() => dummy++)
expect(dummy).toBe(0)
Events.updated.emit()
expect(dummy).toBe(1)
Events.updated.emit()
expect(dummy).toBe(1)
})
// 多事件收发
it('Multiple events', () => {
let dummy1 = 100
let dummy2 = '200'
Events.clicked.on(val => dummy1 = val.x + val.y)
Events.wang.on((sVal, nVal) => dummy2 = sVal + nVal)
Events.wang.emit('1', 2)
expect(dummy1).toBe(100)
expect(dummy2).toBe('12')
Events.clicked.emit({ x: 2, y: 3 })
expect(dummy1).toBe(5)
expect(dummy2).toBe('12')
})
// 覆盖保护
it('Cover protection', () => {
let dummy = 0, errObj
const oldClicked = Events.clicked
Events.updated.on(() => dummy++)
try {
; (Events.updated as any) = undefined
} catch (err) {
errObj = err
}
expect(errObj).not.toBe(undefined)
Events.updated.emit()
expect(dummy).toBe(1)
})
// 删除保护
it('Delete property protection', () => {
let dummy = 0, errObj
const oldClicked = Events.clicked
Events.updated.on(() => dummy++)
try {
delete (Events as any).updated
} catch (err) {
errObj = err
}
expect(errObj).not.toBe(undefined)
Events.updated.emit()
expect(dummy).toBe(1)
})