1 |
|
2 | var _, register, reset, restore, sandbox, sinon, spy, stub;
|
3 |
|
4 | sinon = require("sinon");
|
5 |
|
6 | _ = require("lodash");
|
7 |
|
8 | sandbox = [];
|
9 |
|
10 | register = function(type, obj, method, func) {
|
11 | var e, item;
|
12 | item = null;
|
13 | try {
|
14 | if (type === "stub" && !_.isEmpty(func)) {
|
15 | item = sinon.stub(obj, method).callsFake(func);
|
16 | } else {
|
17 | item = sinon[type].apply(sinon, [obj, method, func]);
|
18 | }
|
19 | sandbox.push(item);
|
20 | } catch (error) {
|
21 | e = error;
|
22 | if (/already wrapped/i.test(e.message)) {
|
23 | item = obj[method];
|
24 | } else {
|
25 | throw e;
|
26 | }
|
27 | }
|
28 | return item;
|
29 | };
|
30 |
|
31 | stub = function(obj, method, func) {
|
32 | return register('stub', obj, method, func);
|
33 | };
|
34 |
|
35 | spy = function(obj, method) {
|
36 | return register('spy', obj, method);
|
37 | };
|
38 |
|
39 | reset = function() {
|
40 | return _.each(sandbox, function(stub_or_spy) {
|
41 | return stub_or_spy.reset();
|
42 | });
|
43 | };
|
44 |
|
45 | restore = function() {
|
46 | return _.each(sandbox, function(stub) {
|
47 | if (stub.restore) {
|
48 | return stub.restore();
|
49 | }
|
50 | });
|
51 | };
|
52 |
|
53 | module.exports = {
|
54 | stub: stub,
|
55 | spy: spy,
|
56 | reset: reset,
|
57 | restore: restore
|
58 | };
|