Skip to content

Commit

Permalink
fix: muk can mock accessor descriptor now
Browse files Browse the repository at this point in the history
  • Loading branch information
popomore committed Sep 16, 2015
1 parent 644b26b commit 73001d7
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
7 changes: 5 additions & 2 deletions lib/method.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
'use strict';

// keep track of mocks
var mocks = [];

Expand All @@ -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;
};

Expand All @@ -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 = [];
Expand Down
25 changes: 25 additions & 0 deletions test/method-test.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
'use strict';

var muk = require('..');
var assert = require('assert');
var fs = require('fs');
Expand Down Expand Up @@ -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);
}

0 comments on commit 73001d7

Please sign in to comment.