/
spy.js
459 lines (382 loc) · 15.1 KB
/
spy.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
"use strict";
var createBehavior = require("./behavior").create;
var extend = require("./util/core/extend");
var functionName = require("./util/core/function-name");
var functionToString = require("./util/core/function-to-string");
var getPropertyDescriptor = require("./util/core/get-property-descriptor");
var sinonMatch = require("./match");
var deepEqual = require("./util/core/deep-equal").use(sinonMatch);
var spyCall = require("./call");
var wrapMethod = require("./util/core/wrap-method");
var sinonFormat = require("./util/core/format");
var valueToString = require("./util/core/value-to-string");
/* cache references to library methods so that they also can be stubbed without problems */
var push = Array.prototype.push;
var slice = Array.prototype.slice;
var filter = Array.prototype.filter;
var ErrorConstructor = Error.prototype.constructor;
var callId = 0;
function spy(object, property, types) {
var descriptor, methodDesc;
if (!property && typeof object === "function") {
return spy.create(object);
}
if (!object && !property) {
return spy.create(function () { });
}
if (!types) {
return wrapMethod(object, property, spy.create(object[property]));
}
descriptor = {};
methodDesc = getPropertyDescriptor(object, property);
types.forEach(function (type) {
descriptor[type] = spy.create(methodDesc[type]);
});
return wrapMethod(object, property, descriptor);
}
function incrementCallCount() {
this.called = true;
this.callCount += 1;
this.notCalled = false;
this.calledOnce = this.callCount === 1;
this.calledTwice = this.callCount === 2;
this.calledThrice = this.callCount === 3;
}
function createCallProperties() {
this.firstCall = this.getCall(0);
this.secondCall = this.getCall(1);
this.thirdCall = this.getCall(2);
this.lastCall = this.getCall(this.callCount - 1);
}
function createProxy(func, proxyLength) {
// Retain the function length:
var p;
if (proxyLength) {
// Do not change this to use an eval. Projects that depend on sinon block the use of eval.
// ref: https://github.com/sinonjs/sinon/issues/710
switch (proxyLength) {
/*eslint-disable no-unused-vars, max-len*/
case 1: p = function proxy(a) { return p.invoke(func, this, slice.call(arguments)); }; break;
case 2: p = function proxy(a, b) { return p.invoke(func, this, slice.call(arguments)); }; break;
case 3: p = function proxy(a, b, c) { return p.invoke(func, this, slice.call(arguments)); }; break;
case 4: p = function proxy(a, b, c, d) { return p.invoke(func, this, slice.call(arguments)); }; break;
case 5: p = function proxy(a, b, c, d, e) { return p.invoke(func, this, slice.call(arguments)); }; break;
case 6: p = function proxy(a, b, c, d, e, f) { return p.invoke(func, this, slice.call(arguments)); }; break;
case 7: p = function proxy(a, b, c, d, e, f, g) { return p.invoke(func, this, slice.call(arguments)); }; break;
case 8: p = function proxy(a, b, c, d, e, f, g, h) { return p.invoke(func, this, slice.call(arguments)); }; break;
case 9: p = function proxy(a, b, c, d, e, f, g, h, i) { return p.invoke(func, this, slice.call(arguments)); }; break;
case 10: p = function proxy(a, b, c, d, e, f, g, h, i, j) { return p.invoke(func, this, slice.call(arguments)); }; break;
case 11: p = function proxy(a, b, c, d, e, f, g, h, i, j, k) { return p.invoke(func, this, slice.call(arguments)); }; break;
case 12: p = function proxy(a, b, c, d, e, f, g, h, i, j, k, l) { return p.invoke(func, this, slice.call(arguments)); }; break;
default: p = function proxy() { return p.invoke(func, this, slice.call(arguments)); }; break;
/*eslint-enable*/
}
} else {
p = function proxy() {
return p.invoke(func, this, slice.call(arguments));
};
}
p.isSinonProxy = true;
return p;
}
var uuid = 0;
// Public API
var spyApi = {
formatters: require("./spy-formatters"),
reset: function () {
if (this.invoking) {
var err = new Error("Cannot reset Sinon function while invoking it. " +
"Move the call to .reset outside of the callback.");
err.name = "InvalidResetException";
throw err;
}
this.called = false;
this.notCalled = true;
this.calledOnce = false;
this.calledTwice = false;
this.calledThrice = false;
this.callCount = 0;
this.firstCall = null;
this.secondCall = null;
this.thirdCall = null;
this.lastCall = null;
this.args = [];
this.returnValues = [];
this.thisValues = [];
this.exceptions = [];
this.callIds = [];
this.errorsWithCallStack = [];
if (this.fakes) {
this.fakes.forEach(function (fake) {
if (fake.resetHistory) {
fake.resetHistory();
} else {
fake.reset();
}
});
}
return this;
},
create: function create(func, spyLength) {
var name;
if (typeof func !== "function") {
func = function () { };
} else {
name = functionName(func);
}
if (!spyLength) {
spyLength = func.length;
}
var proxy = createProxy(func, spyLength);
extend(proxy, spy);
delete proxy.create;
extend(proxy, func);
proxy.reset();
proxy.prototype = func.prototype;
proxy.displayName = name || "spy";
proxy.toString = functionToString;
proxy.instantiateFake = spy.create;
proxy.id = "spy#" + uuid++;
return proxy;
},
invoke: function invoke(func, thisValue, args) {
var matchings = this.matchingFakes(args);
var currentCallId = callId++;
var exception, returnValue;
incrementCallCount.call(this);
push.call(this.thisValues, thisValue);
push.call(this.args, args);
push.call(this.callIds, currentCallId);
matchings.forEach(function (matching) {
incrementCallCount.call(matching);
push.call(matching.thisValues, thisValue);
push.call(matching.args, args);
push.call(matching.callIds, currentCallId);
});
// Make call properties available from within the spied function:
createCallProperties.call(this);
matchings.forEach(function (matching) {
createCallProperties.call(matching);
});
try {
this.invoking = true;
returnValue = (this.func || func).apply(thisValue, args);
var thisCall = this.getCall(this.callCount - 1);
if (thisCall.calledWithNew() && typeof returnValue !== "object") {
returnValue = thisValue;
}
} catch (e) {
exception = e;
} finally {
delete this.invoking;
}
push.call(this.exceptions, exception);
push.call(this.returnValues, returnValue);
matchings.forEach(function (matching) {
push.call(matching.exceptions, exception);
push.call(matching.returnValues, returnValue);
});
var err = new ErrorConstructor();
// 1. Please do not get stack at this point. It may be so very slow, and not actually used
// 2. PhantomJS does not serialize the stack trace until the error has been thrown:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Stack
try {
throw err;
} catch (e) {/* empty */}
push.call(this.errorsWithCallStack, err);
matchings.forEach(function (matching) {
push.call(matching.errorsWithCallStack, err);
});
// Make return value and exception available in the calls:
createCallProperties.call(this);
matchings.forEach(function (matching) {
createCallProperties.call(matching);
});
if (exception !== undefined) {
throw exception;
}
return returnValue;
},
named: function named(name) {
this.displayName = name;
return this;
},
getCall: function getCall(i) {
if (i < 0 || i >= this.callCount) {
return null;
}
return spyCall(this, this.thisValues[i], this.args[i],
this.returnValues[i], this.exceptions[i],
this.callIds[i], this.errorsWithCallStack[i]);
},
getCalls: function () {
var calls = [];
var i;
for (i = 0; i < this.callCount; i++) {
calls.push(this.getCall(i));
}
return calls;
},
calledBefore: function calledBefore(spyFn) {
if (!this.called) {
return false;
}
if (!spyFn.called) {
return true;
}
return this.callIds[0] < spyFn.callIds[spyFn.callIds.length - 1];
},
calledAfter: function calledAfter(spyFn) {
if (!this.called || !spyFn.called) {
return false;
}
return this.callIds[this.callCount - 1] > spyFn.callIds[0];
},
calledImmediatelyBefore: function calledImmediatelyBefore(spyFn) {
if (!this.called || !spyFn.called) {
return false;
}
return this.callIds[this.callCount - 1] === spyFn.callIds[spyFn.callCount - 1] - 1;
},
calledImmediatelyAfter: function calledImmediatelyAfter(spyFn) {
if (!this.called || !spyFn.called) {
return false;
}
return this.callIds[this.callCount - 1] === spyFn.callIds[spyFn.callCount - 1] + 1;
},
withArgs: function () {
var args = slice.call(arguments);
if (this.fakes) {
var matching = this.matchingFakes(args, true).pop();
if (matching) {
return matching;
}
} else {
this.fakes = [];
}
var original = this;
var fake = this.instantiateFake();
fake.matchingArguments = args;
fake.parent = this;
push.call(this.fakes, fake);
if (original.defaultBehavior && original.defaultBehavior.promiseLibrary) {
fake.defaultBehavior = fake.defaultBehavior || createBehavior(fake);
fake.defaultBehavior.promiseLibrary = original.defaultBehavior.promiseLibrary;
}
fake.withArgs = function () {
return original.withArgs.apply(original, arguments);
};
original.args.forEach(function (arg, i) {
if (!fake.matches(arg)) {
return;
}
incrementCallCount.call(fake);
push.call(fake.thisValues, original.thisValues[i]);
push.call(fake.args, arg);
push.call(fake.returnValues, original.returnValues[i]);
push.call(fake.exceptions, original.exceptions[i]);
push.call(fake.callIds, original.callIds[i]);
});
createCallProperties.call(fake);
return fake;
},
matchingFakes: function (args, strict) {
return filter.call(this.fakes || [], function (fake) {
return fake.matches(args, strict);
});
},
matches: function (args, strict) {
var margs = this.matchingArguments;
if (margs.length <= args.length &&
deepEqual(margs, args.slice(0, margs.length))) {
return !strict || margs.length === args.length;
}
return undefined;
},
printf: function (format) {
var spyInstance = this;
var args = slice.call(arguments, 1);
var formatter;
return (format || "").replace(/%(.)/g, function (match, specifyer) {
formatter = spyApi.formatters[specifyer];
if (typeof formatter === "function") {
return formatter.call(null, spyInstance, args);
} else if (!isNaN(parseInt(specifyer, 10))) {
return sinonFormat(args[specifyer - 1]);
}
return "%" + specifyer;
});
}
};
function delegateToCalls(method, matchAny, actual, notCalled) {
spyApi[method] = function () {
if (!this.called) {
if (notCalled) {
return notCalled.apply(this, arguments);
}
return false;
}
var currentCall;
var matches = 0;
for (var i = 0, l = this.callCount; i < l; i += 1) {
currentCall = this.getCall(i);
if (currentCall[actual || method].apply(currentCall, arguments)) {
matches += 1;
if (matchAny) {
return true;
}
}
}
return matches === this.callCount;
};
}
delegateToCalls("calledOn", true);
delegateToCalls("alwaysCalledOn", false, "calledOn");
delegateToCalls("calledWith", true);
delegateToCalls("calledWithMatch", true);
delegateToCalls("alwaysCalledWith", false, "calledWith");
delegateToCalls("alwaysCalledWithMatch", false, "calledWithMatch");
delegateToCalls("calledWithExactly", true);
delegateToCalls("alwaysCalledWithExactly", false, "calledWithExactly");
delegateToCalls("neverCalledWith", false, "notCalledWith", function () {
return true;
});
delegateToCalls("neverCalledWithMatch", false, "notCalledWithMatch", function () {
return true;
});
delegateToCalls("threw", true);
delegateToCalls("alwaysThrew", false, "threw");
delegateToCalls("returned", true);
delegateToCalls("alwaysReturned", false, "returned");
delegateToCalls("calledWithNew", true);
delegateToCalls("alwaysCalledWithNew", false, "calledWithNew");
delegateToCalls("callArg", false, "callArgWith", function () {
throw new Error(this.toString() + " cannot call arg since it was not yet invoked.");
});
spyApi.callArgWith = spyApi.callArg;
delegateToCalls("callArgOn", false, "callArgOnWith", function () {
throw new Error(this.toString() + " cannot call arg since it was not yet invoked.");
});
spyApi.callArgOnWith = spyApi.callArgOn;
delegateToCalls("throwArg", false, "throwArg", function () {
throw new Error(this.toString() + " cannot throw arg since it was not yet invoked.");
});
delegateToCalls("yield", false, "yield", function () {
throw new Error(this.toString() + " cannot yield since it was not yet invoked.");
});
// "invokeCallback" is an alias for "yield" since "yield" is invalid in strict mode.
spyApi.invokeCallback = spyApi.yield;
delegateToCalls("yieldOn", false, "yieldOn", function () {
throw new Error(this.toString() + " cannot yield since it was not yet invoked.");
});
delegateToCalls("yieldTo", false, "yieldTo", function (property) {
throw new Error(this.toString() + " cannot yield to '" + valueToString(property) +
"' since it was not yet invoked.");
});
delegateToCalls("yieldToOn", false, "yieldToOn", function (property) {
throw new Error(this.toString() + " cannot yield to '" + valueToString(property) +
"' since it was not yet invoked.");
});
extend(spy, spyApi);
spy.spyCall = spyCall;
module.exports = spy;