diff --git a/lib/method.js b/lib/method.js index 9cc6c0d..06f7414 100644 --- a/lib/method.js +++ b/lib/method.js @@ -1,3 +1,5 @@ +'use strict'; + // keep track of mocks var mocks = []; @@ -13,9 +15,10 @@ var method = module.exports = function mockMethod(obj, key, method) { mocks.push({ obj: obj, key: key, - original: obj[key], + descriptor: Object.getOwnPropertyDescriptor(obj, key), exist: key in obj }); + delete obj[key]; obj[key] = method === undefined ? function() {} : method; }; @@ -29,7 +32,7 @@ method.restore = function restoreMocks() { if (!m.exist) { delete m.obj[m.key]; } else { - m.obj[m.key] = m.original; + Object.defineProperty(m.obj, m.key, m.descriptor); } } mocks = []; diff --git a/test/method-test.js b/test/method-test.js index 5083558..f4d7404 100644 --- a/test/method-test.js +++ b/test/method-test.js @@ -1,3 +1,5 @@ +'use strict'; + var muk = require('..'); var assert = require('assert'); var fs = require('fs'); @@ -87,6 +89,29 @@ describe('Mock property', function () { }); }); +describe('Mock getter', function() { + var obj = { + get a() { + return 1; + } + }; + + it('Contains original getter', function() { + assert.equal(obj.a, 1, 'property a of obj is 1'); + }); + + it('Methods are new getter after mocked', function() { + muk(obj, 'a', 2); + assert.equal(obj.a, 2, 'property a of obj is equal to mock'); + }); + + it('Should have original getter after muk.restore()', function() { + muk(obj, 'a', 2); + muk.restore(); + assert.equal(obj.a, 1, 'property a of obj is equal to mock'); + }); +}); + function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }