-
-
Notifications
You must be signed in to change notification settings - Fork 6.4k
/
index.js
77 lines (67 loc) · 1.89 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
/**
* Copyright (c) 2014-present, Facebook, Inc. 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, installCommonGlobals} from 'jest-util';
import mock from 'jest-mock';
type Timer = {|
id: number,
ref: () => Timer,
unref: () => Timer,
|};
class NodeEnvironment {
context: ?vm$Context;
fakeTimers: ?FakeTimers;
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.Promise = Promise;
global.setInterval = setInterval;
global.setTimeout = setTimeout;
installCommonGlobals(global, config.globals);
this.moduleMocker = new mock.ModuleMocker(global);
this.fakeTimers = new FakeTimers({
config,
global,
moduleMocker: this.moduleMocker,
});
}
setup(): Promise<void> {
return Promise.resolve();
}
teardown(): Promise<void> {
if (this.fakeTimers) {
this.fakeTimers.dispose();
}
this.context = null;
this.fakeTimers = null;
return Promise.resolve();
}
// Disabling rule as return type depends on script's return type.
/* eslint-disable flowtype/no-weak-types */
runScript(script: Script): ?any {
/* eslint-enable flowtype/no-weak-types */
if (this.context) {
return script.runInContext(this.context);
}
return null;
}
}
module.exports = NodeEnvironment;