Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ declare namespace mm {
*/
function empty(mod: any, method: string, timeout?: number): MockMate;

/**
* spy a function
*/
function spy(mod: any, method: string): void;

/**
* mock return callback(null, data1, data2).
*/
Expand Down
6 changes: 5 additions & 1 deletion lib/mm.js
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,11 @@ exports.empty = function(mod, method, timeout) {
*/
exports.spy = function(mod, method) {
if (typeof mod[method] !== 'function') throw new Error(`spy target ${method} is not a function`);
mock(mod, method, mod[method]);
const originalFn = mod[method];
const wrap = function proxy() {
return originalFn.apply(this, arguments);
};
mock(mod, method, wrap);
};

/**
Expand Down
18 changes: 17 additions & 1 deletion test/mm.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1125,8 +1125,24 @@ describe('test/mm.test.js', () => {
target.add.calledArguments.should.eql([[ 1, 1 ], [ 2, 2 ]]);
target.add.lastCalledArguments.should.eql([ 2, 2 ]);
});
});

it('should reset spy statistics after restore', () => {
const target = {
add(a, b) {
return a + b;
},
};
mm.spy(target, 'add');
target.add(1, 1);
target.add.called.should.equal(1);
target.add.calledArguments.should.eql([[ 1, 1 ]]);
target.add.lastCalledArguments.should.eql([ 1, 1 ]);
mm.restore();
assert.strictEqual(target.add.called, undefined);
assert.strictEqual(target.add.calledArguments, undefined);
assert.strictEqual(target.add.lastCalledArguments, undefined);
});
});
});

const enable = require('enable');
Expand Down