-
Notifications
You must be signed in to change notification settings - Fork 14
/
window.js
88 lines (83 loc) · 2.44 KB
/
window.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
import mockFunction from './mock/function';
import locationFactory from './mock/location';
import proxyFactory from './mock/proxy';
import Storage from './mock/storage';
const originalWindow = window;
let location = locationFactory(originalWindow.location.href);
let localStorage = new Storage();
let sessionStorage = new Storage();
let holder = {};
function noop() {}
export const mockProxyHandler = {
get(target, name, receiver) {
switch (name) {
case 'location':
return location;
case 'localStorage':
return localStorage;
case 'sessionStorage':
return sessionStorage;
case 'window':
return receiver;
case 'alert':
case 'confirm':
case 'prompt':
return name in holder ? holder[name] : noop;
case 'onerror':
case 'onunhandledrejection':
// Always return the original error handler
return Reflect.get(target, name);
default:
if (name in holder) {
return holder[name];
}
if (typeof window[name] === 'function') {
return mockFunction(target[name], target);
}
if (typeof window[name] === 'object' && window[name] !== null) {
let proxy = proxyFactory(window[name]);
holder[name] = proxy;
return proxy;
}
return target[name];
}
},
set(target, name, value, receiver) {
switch (name) {
case 'location':
// setting window.location is equivalent to setting window.location.href
receiver.location.href = value;
return true;
case 'onerror':
case 'onunhandledrejection':
// onerror always must live on the real window object to work
return Reflect.set(target, name, value);
default:
holder[name] = value;
return true;
}
},
has(target, prop) {
return prop in holder || prop in target;
},
deleteProperty(target, prop) {
delete holder[prop];
delete target[prop];
return true;
},
getOwnPropertyDescriptor(target, property) {
return (
Reflect.getOwnPropertyDescriptor(holder, property) ??
Reflect.getOwnPropertyDescriptor(target, property)
);
},
defineProperty(target, property, attributes) {
return Reflect.defineProperty(holder, property, attributes);
},
};
export function reset() {
location = locationFactory(originalWindow.location.href);
localStorage = new Storage();
sessionStorage = new Storage();
holder = {};
}