forked from MauriceButler/fraudster
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
106 lines (84 loc) · 2.57 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
var Module = require('module');
function fakeLoader(request, parent, isMain) {
if (!this.originalLoader) {
throw new Error('Loader has not been replaced');
}
if (this.registeredMocks[request]) {
return this.registeredMocks[request];
}
if (!this.registeredAllowables[request]) {
if (this.options.warnOnUnregistered) {
console.warn('WARNING: loading non-allowed module: ' + request);
}
if (this.options.errorOnUnregistered) {
throw new Error('ERROR: loading non-allowed module: ' + request);
}
}
return this.originalLoader(request, parent, isMain);
}
function Fraudster(options){
this.registeredMocks = {};
this.registeredAllowables = {};
this.originalLoader = null;
this.originalCache = null;
this.options = {
warnOnReplace: false,
warnOnUnregistered: true
};
for(var key in options){
this.options[key] = options[key];
}
}
Fraudster.prototype.enable = function () {
if (this.originalLoader) {
return;
}
this.originalLoader = Module._load;
Module._load = fakeLoader.bind(this);
};
Fraudster.prototype.disable = function () {
if (!this.originalLoader) {
return;
}
Module._load = this.originalLoader;
this.originalLoader = null;
};
Fraudster.prototype.registerMock = function (key, mock) {
if (this.registeredMocks.hasOwnProperty(key)) {
if(this.options.warnOnReplace){
console.warn('WARNING: Replacing existing mock for module: ' + key);
}
if(this.options.errorOnReplace){
throw new Error('ERROR: Replacing existing mock for module: ' + key);
}
}
this.registeredMocks[key] = mock;
};
Fraudster.prototype.deregisterMock = function (key) {
if (this.registeredMocks.hasOwnProperty(key)) {
delete this.registeredMocks[key];
}
};
Fraudster.prototype.registerAllowable = function (key) {
this.registeredAllowables[key] = true;
};
Fraudster.prototype.registerAllowables = function (keys) {
var fraudster = this;
keys.forEach(function (key) {
fraudster.registerAllowable(key);
});
};
Fraudster.prototype.deregisterAllowable = function (key) {
delete this.registeredAllowables[key];
};
Fraudster.prototype.deregisterAllowables = function (keys) {
var fraudster = this;
keys.forEach(function (key) {
fraudster.deregisterAllowable(key);
});
};
Fraudster.prototype.deregisterAll = function (){
this.registeredMocks = {};
this.registeredAllowables = {};
};
module.exports = Fraudster;