Skip to content

Commit

Permalink
fix: spy statistics is not reset after restore (#55)
Browse files Browse the repository at this point in the history
  • Loading branch information
gxkl committed Apr 2, 2023
1 parent fcb0e10 commit 97dcf42
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
5 changes: 5 additions & 0 deletions index.d.ts
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
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
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

0 comments on commit 97dcf42

Please sign in to comment.