/
index.js
109 lines (95 loc) · 2.65 KB
/
index.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {Script} from 'vm';
import type {ProjectConfig} from 'types/Config';
import type {Global} from 'types/Global';
import type {ModuleMocker} from 'jest-mock';
import vm from 'vm';
import {FakeTimers, FakeTimersLolex, installCommonGlobals} from 'jest-util';
import mock from 'jest-mock';
type Timer = {|
id: number,
ref: () => Timer,
unref: () => Timer,
|};
class NodeEnvironment {
context: ?vm$Context;
fakeTimers: ?FakeTimers<Timer>;
fakeTimersLolex: ?FakeTimersLolex;
global: ?Global;
moduleMocker: ?ModuleMocker;
constructor(config: ProjectConfig) {
this.context = vm.createContext();
const global = (this.global = vm.runInContext(
'this',
Object.assign(this.context, config.testEnvironmentOptions),
));
global.global = global;
global.clearInterval = clearInterval;
global.clearTimeout = clearTimeout;
global.setInterval = setInterval;
global.setTimeout = setTimeout;
global.ArrayBuffer = ArrayBuffer;
// URL and URLSearchParams are global in Node >= 10
if (typeof URL !== 'undefined' && typeof URLSearchParams !== 'undefined') {
/* global URL, URLSearchParams */
global.URL = URL;
global.URLSearchParams = URLSearchParams;
}
installCommonGlobals(global, config.globals);
this.moduleMocker = new mock.ModuleMocker(global);
const timerIdToRef = (id: number) => ({
id,
ref() {
return this;
},
unref() {
return this;
},
});
const timerRefToId = (timer: Timer): ?number => (timer && timer.id) || null;
const timerConfig = {
idToRef: timerIdToRef,
refToId: timerRefToId,
};
this.fakeTimers = new FakeTimers({
config,
global,
moduleMocker: this.moduleMocker,
timerConfig,
});
this.fakeTimersLolex = new FakeTimersLolex({
config,
global,
});
}
setup(): Promise<void> {
return Promise.resolve();
}
teardown(): Promise<void> {
if (this.fakeTimers) {
this.fakeTimers.dispose();
}
if (this.fakeTimersLolex) {
this.fakeTimersLolex.dispose();
}
this.context = null;
this.fakeTimers = null;
this.fakeTimersLolex = null;
return Promise.resolve();
}
// Disabling rule as return type depends on script's return type.
runScript(script: Script): ?any {
if (this.context) {
return script.runInContext(this.context);
}
return null;
}
}
module.exports = NodeEnvironment;