-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathindex.js
120 lines (106 loc) · 2.83 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
110
111
112
113
114
115
116
117
118
119
120
function buildThenable() {
return {
onFulfilled: [],
onRejected: [],
onFinally: [],
then: function(onFulfill, onReject) {
try {
if (this.resolved && !this.rejected) {
var returned = onFulfill(this.resolveValue);
// promise returned, return that for next handler in chain
if (returned && returned.then) {
return returned;
}
// update resolve value for next promise in chain
if (returned !== undefined) {
this.resolveValue = returned;
}
return this;
}
} catch(error) {
if (error.constructor.name.match(/AssertionError/)) {
throw error;
}
this.rejectValue = error;
this.rejected = true;
}
if (this.rejected && onReject) {
return this.catch(onReject);
}
if (!this.rejected && onFulfill) {
this.onFulfilled.push(onFulfill);
}
if (!this.resolved && onReject) {
this.onRejected.push(onReject);
}
return this;
},
catch: function(onReject) {
if (this.rejected) {
try {
const value = onReject(this.rejectValue);
if (value && value.then) {
return value;
}
this.resolved = true;
this.rejected = false;
this.resolveValue = value;
this.rejectValue = undefined;
} catch (e) {
this.rejectValue = e;
}
return this;
}
if (!this.resolved) {
this.onRejected.push(onReject);
}
return this;
},
finally: function(callback) {
if (this.resolved || this.rejected) {
callback();
return;
}
this.onFinally.push(callback);
}
};
}
function setup(sinon) {
function resolves(value) {
this.thenable.resolved = true;
this.thenable.rejected = false;
this.thenable.resolveValue = value;
this.thenable.onFulfilled
.concat(this.thenable.onFinally)
.forEach(function(callback) {
callback(value);
});
return this;
}
function rejects(value) {
this.thenable.rejected = true;
this.thenable.resolved = false;
this.thenable.rejectValue = value;
this.thenable.onRejected
.concat(this.thenable.onFinally)
.forEach(function(callback) {
callback(value);
});
return this;
}
sinon.stub.returnsPromise = function() {
this.resolves = resolves;
this.rejects = rejects;
var thenable = buildThenable();
this.thenable = thenable;
this.returns(thenable);
return this;
};
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = setup;
} else if (typeof window !== 'undefined') {
if(typeof window.sinon !== 'undefined') setup(window.sinon);
} else {
if(typeof this.sinon !== 'undefined') setup(this.sinon);
}