From f2c39c1e9ec5f5be80e614d64b8e436ed01cc4f4 Mon Sep 17 00:00:00 2001 From: Cemen Istomin Date: Mon, 16 Nov 2015 14:35:38 +0300 Subject: [PATCH] Added ability to remove spies from object methods --- lib/spy.js | 16 +++++++++++++++- test/spies.js | 17 +++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/lib/spy.js b/lib/spy.js index 87a331b..4254e80 100644 --- a/lib/spy.js +++ b/lib/spy.js @@ -108,7 +108,21 @@ module.exports = function (chai, _) { var methodNames = Array.prototype.slice.call(arguments, 1); methodNames.forEach(function(methodName) { - object[methodName] = chai.spy(object[methodName]); + var originalMethod = object[methodName]; + var spy = object[methodName] = chai.spy(originalMethod); + + /** + * # chai.spy.removeSpy () + * + * Removes this spy from object method. Useful when spying on system APIs. + * Only exists in spies that installed with spy.on() + * + * var spy = chai.spy.on(console, 'log'); + * console.log.removeSpy(); + */ + spy.removeSpy = function() { + object[methodName] = originalMethod; + } }); return object; diff --git a/test/spies.js b/test/spies.js index bb6bd14..dd0a955 100644 --- a/test/spies.js +++ b/test/spies.js @@ -444,4 +444,21 @@ describe('Chai Spies', function () { spy.__spy.name.should.be.equal(name); }); }); + + describe('remove method', function() { + it('should remove spy from object', function() { + var testObj = { + testMethod: function() { return "foo"; } + }; + + chai.spy.on(testObj, "testMethod"); + var spy = testObj.testMethod; + testObj.testMethod(); + spy.should.have.been.called.once; // triggers when spy is installed + + spy.removeSpy(); + testObj.testMethod(); + spy.should.have.been.called.once; // does not trigger when spy is removed + }); + }); });