-
Notifications
You must be signed in to change notification settings - Fork 0
/
i-spy.js
77 lines (60 loc) · 1.28 KB
/
i-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
'use strict';
function thrower(err) {
return function () { throw err; }
}
function returner(obj) {
return function () { return obj; }
}
function createSpy(fn) {
var fake = fn;
if (fake !== void 0 && typeof(fn) !== 'function') {
if (fn instanceof Error) {
fake = thrower(fn);
} else {
fake = returner(fn);
}
}
function spy() {
var spyArgs = [].slice.call(arguments);
spy.calls.push(spyArgs);
spy.context = this;
return fake && fake.apply(spy.context, spyArgs);
}
spy.calls = [];
spy.reset = function reset() {
spy.calls = [];
};
// Checkers
spy.callCount = function callCount() {
return spy.calls.length;
}
spy.wasCalled = function wasCalled() {
return spy.calls.length > 0;
};
spy.wasNotCalled = function wasNotCalled() {
return spy.calls.length === 0;
};
spy.firstCall = function firstCall() {
return spy.calls[0];
};
spy.lastCall = function lastCall() {
return spy.calls[spy.calls.length - 1];
};
// Fluent interface
spy.thatThrows = function thatThrows(err) {
fake = thrower(err);
return spy;
};
spy.thatReturns = function thatReturns(returnValue) {
fake = returner(returnValue);
return spy;
};
spy.thatCalls = function thatCalls(fn) {
fake = fn;
return spy;
};
return spy;
}
module.exports = {
createSpy: createSpy
};