Repository navigation
Expand file tree
/
Copy pathsandbox.js
More file actions
executable file
·77 lines (63 loc) · 1.68 KB
/
Copy pathsandbox.js
File metadata and controls
executable file
·77 lines (63 loc) · 1.68 KB
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
/**
* Sinon.js && Parse.com compatible sandbox and stub implementation
* @type {{create: function}}
*/
var sandbox = {
create: function () {
return new Sandbox();
}
};
function Sandbox() {
this.stubs = {};
}
/**
* Stub method, compatible with Parse.com environment
*
* @param object
* @param method
* @param func
* @param key
*/
Sandbox.prototype.stub = function stub(object, method, func, key) {
if (typeof method !== 'string') {
throw Error("#stub() 'method' argument should be a string");
}
if (!(method in object || typeof object[method] !== 'function')) {
throw Error('Stubbing element is not a function');
}
if (!key) {
key = uuid();
}
this.stubs[key] = new Stub(object, method, object[method]);
object[method] = func;
};
Sandbox.prototype.restore = function restore() {
var keys = Object.keys(this.stubs),
length = keys.length,
i;
for (i = 0; i < length; i++) {
this.stubs[keys[i]].restore();
}
};
Sandbox.prototype.invokeOriginal = function (key, args) {
return this.stubs[key].invokeOriginal(args);
};
function Stub(object, method, func) {
this.object = object;
this.method = method;
this.func = func;
}
Stub.prototype.restore = function () {
return this.object[this.method] = this.func;
};
Stub.prototype.invokeOriginal = function (args) {
return this.func.apply(this.object, args)
};
function uuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,
function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
module.exports = sandbox;