-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
90 lines (66 loc) · 1.86 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
var BaseGateway = require('42-cent-base').BaseGateway;
var P = require('bluebird');
var util = require('util');
var instance;
var methods = Object.keys(BaseGateway.prototype);
function MockGateway (options) {
this.stubs = [];
BaseGateway.call(this, options);
}
util.inherits(MockGateway, BaseGateway);
function factory (options) {
//forcing singleton
if (!instance) {
instance = new MockGateway(options);
}
return instance;
}
methods.forEach(function (meth) {
MockGateway.prototype[meth] = function () {
var args = [].slice.call(arguments);
var stub = this.stubs.filter(function (st) {
return meth === st.method;
});
if (stub.length === 0) {
throw new Error('Unexpected call of gateway ' + meth + ' with ' + JSON.stringify((args)));
}
stub = stub[0];
if (!stub.resolveValue && !stub.rejectValue) {
throw new Error('Unhandled call to the stub of ' + stub.method);
}
stub.calls.push(args);
return stub.resolveValue ? P.resolve(stub.resolveValue) : P.reject(stub.rejectValue);
}
});
exports.factory = factory;
exports.clean = function clean () {
factory().stubs = [];
};
function Stub (method) {
this.calls = [];
this.method = method;
}
Stub.prototype.rejectWith = function rejectWith (value) {
this.rejectValue = value;
return this;
};
Stub.prototype.resolveWith = function resolveWith (value) {
this.resolveValue = value;
return this;
};
exports.when = function when (method) {
var stub;
var matching;
if (method.indexOf(method) === -1) {
throw new Error(method, ' is not part of gateway implementation');
}
matching = factory().stubs.filter(function (st) {
return st.method === method;
});
while (matching.length > 0) {
factory().stubs.splice(factory().stubs.indexOf(matching.pop()), 1);
}
stub = new Stub(method);
factory().stubs.push(stub);
return stub;
};