From 97dcf42d07b5933ce1ef87d1e6fd8c94bd41dcf6 Mon Sep 17 00:00:00 2001 From: Gxkl Date: Sun, 2 Apr 2023 22:09:05 +0800 Subject: [PATCH] fix: spy statistics is not reset after restore (#55) --- index.d.ts | 5 +++++ lib/mm.js | 6 +++++- test/mm.test.js | 18 +++++++++++++++++- 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/index.d.ts b/index.d.ts index 021c5d1..5030c34 100644 --- a/index.d.ts +++ b/index.d.ts @@ -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). */ diff --git a/lib/mm.js b/lib/mm.js index 6af325c..f14ec3d 100644 --- a/lib/mm.js +++ b/lib/mm.js @@ -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); }; /** diff --git a/test/mm.test.js b/test/mm.test.js index 3a28fad..f65e7da 100644 --- a/test/mm.test.js +++ b/test/mm.test.js @@ -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');