-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathCustomTestEnvironment.js
71 lines (61 loc) · 1.72 KB
/
CustomTestEnvironment.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
const JSDOMEnvironment = require('jest-environment-jsdom');
const _ = require('lodash');
class CustomEnvironment extends JSDOMEnvironment {
constructor(config) {
super(config);
}
async setup() {
await super.setup();
this.global.changeUserAgent = () => {
this.dom.reconfigure
};
this.global.mockEnv = (options) => {
const restoreFns = [];
_.each(options, (value, key) => {
if (key === 'url') {
const backupUrl = this.dom.window.location.href;
restoreFns.push(() => {
this.dom.reconfigure({ url: backupUrl });
});
this.dom.reconfigure({ url: value });
return;
}
if (key === 'userAgent') {
const backUserAgent = this.dom.window.navigator.userAgent;
restoreFns.push(() => {
Object.defineProperty(this.dom.window.navigator, 'userAgent', {
value: backUserAgent,
configurable: true,
});
});
Object.defineProperty(this.dom.window.navigator, 'userAgent', {
value,
configurable: true,
});
return;
}
const backupProperty = this.dom.window[key];
restoreFns.push(() => {
Object.defineProperty(this.dom.window, key, {
value: backupProperty,
configurable: true,
});
});
Object.defineProperty(this.dom.window, key, {
value,
configurable: true,
});
});
return () => {
restoreFns.forEach(fn => fn());
};
};
}
async teardown() {
await super.teardown();
}
runScript(script) {
return super.runScript(script);
}
}
module.exports = CustomEnvironment;