From 9b599ca4b948a869dbf9397aeda63c609f21eaad Mon Sep 17 00:00:00 2001 From: Lena Stotska Date: Wed, 10 Jan 2018 17:29:36 +0200 Subject: [PATCH] feat(spy): adds original function body to be exposed in spy.toString() Fixes #26 --- chai-spies.js | 7 ++++--- lib/spy.js | 5 +++-- test/spies.js | 11 +++++++++++ 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/chai-spies.js b/chai-spies.js index 61189c4..175d945 100644 --- a/chai-spies.js +++ b/chai-spies.js @@ -21,7 +21,8 @@ var spy = function (chai, _) { , i = _.inspect , STATE_KEY = typeof Symbol === 'undefined' ? '__state' : Symbol('state') , spyAmount = 0 - , DEFAULT_SANDBOX = new Sandbox(); + , DEFAULT_SANDBOX = new Sandbox() + , noop = function () {}; /** * # Sandbox constructor (function) @@ -189,7 +190,7 @@ var spy = function (chai, _) { name = undefined; } - fn = fn || function () {}; + fn = fn || noop; function makeProxy (length, fn) { switch (length) { @@ -224,7 +225,7 @@ var spy = function (chai, _) { if (l > 0) s += ", " + l + " call" + (l > 1 ? 's' : ''); s += " }"; - return s; + return s + (fn !== noop ? "\n" + fn.toString() : ''); }; proxy.__spy = { diff --git a/lib/spy.js b/lib/spy.js index 92d3b41..b064bb7 100644 --- a/lib/spy.js +++ b/lib/spy.js @@ -16,6 +16,7 @@ module.exports = function (chai, _) { , STATE_KEY = typeof Symbol === 'undefined' ? '__state' : Symbol('state') , spyAmount = 0 , DEFAULT_SANDBOX = new Sandbox() + , noop = function () {} /** * # Sandbox constructor (function) @@ -183,7 +184,7 @@ module.exports = function (chai, _) { name = undefined; } - fn = fn || function () {}; + fn = fn || noop; function makeProxy (length, fn) { switch (length) { @@ -218,7 +219,7 @@ module.exports = function (chai, _) { if (l > 0) s += ", " + l + " call" + (l > 1 ? 's' : ''); s += " }"; - return s; + return s + (fn !== noop ? "\n" + fn.toString() : ''); }; proxy.__spy = { diff --git a/test/spies.js b/test/spies.js index 68451e4..a2d8865 100644 --- a/test/spies.js +++ b/test/spies.js @@ -29,21 +29,32 @@ describe('Chai Spies', function () { it('should print out nice', function() { chai.spy().toString().should.equal("{ Spy }"); }); + it('should show the name', function() { chai.spy('Nikita').toString().should.equal("{ Spy 'Nikita' }"); }); + it('should expose number of invokations', function() { var spy = chai.spy() spy(); // 1 spy(); // 2 spy.toString().should.equal("{ Spy, 2 calls }"); }); + it('should expose name and number of invokations', function() { var spy = chai.spy('Nikita') spy(); // 1 spy.toString().should.equal("{ Spy 'Nikita', 1 call }"); }); + it('should expose original function `toString` representation', function() { + function test(a, b, c) { + return a + b + c; + } + + var spy = chai.spy(test); + spy.toString().should.equal("{ Spy }\n" + test.toString()); + }); }); it('should return the value of the mock function', function() {