-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjest.setup.js
80 lines (71 loc) · 1.57 KB
/
jest.setup.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
class MockPostMessage {
constructor() {
this.handlers = new Map()
}
postMessage(data) {
// 同步处理消息,不使用异步
switch (data.postmate) {
case 'handshake':
this.handleHandshake()
break
case 'request':
this.handleRequest(data)
break
}
}
handleHandshake() {
this.handlers.forEach((handler) =>
handler({
data: {
postmate: 'handshake-reply',
type: 'application/x-postmate-v1+json',
},
origin: 'mock-origin',
source: this,
})
)
}
handleRequest({ property, uid }) {
this.handlers.forEach((handler) =>
handler({
data: {
postmate: 'reply',
type: 'application/x-postmate-v1+json',
property,
uid,
value: this.getMockValue(property),
},
origin: 'mock-origin',
source: this,
})
)
}
getMockValue(property) {
const mockData = {
foo: 'bar',
getData: 'test data',
}
return mockData[property]
}
addEventListener(type, handler) {
this.handlers.set(handler, handler)
}
removeEventListener(type, handler) {
this.handlers.delete(handler)
}
}
// 基础的 window 对象模拟
global.window = {
...global.window,
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
}
// 基础的 DOM 环境模拟
document.createElement = jest.fn(() => ({
appendChild: jest.fn(),
removeChild: jest.fn(),
classList: { add: jest.fn() },
style: {},
}))
// 模拟 postMessage 环境
global.postMessage = jest.fn()