Skip to content

Commit 73001d7

Browse files
committed
fix: muk can mock accessor descriptor now
1 parent 644b26b commit 73001d7

2 files changed

Lines changed: 30 additions & 2 deletions

File tree

lib/method.js

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
'use strict';
2+
13
// keep track of mocks
24
var mocks = [];
35

@@ -13,9 +15,10 @@ var method = module.exports = function mockMethod(obj, key, method) {
1315
mocks.push({
1416
obj: obj,
1517
key: key,
16-
original: obj[key],
18+
descriptor: Object.getOwnPropertyDescriptor(obj, key),
1719
exist: key in obj
1820
});
21+
delete obj[key];
1922
obj[key] = method === undefined ? function() {} : method;
2023
};
2124

@@ -29,7 +32,7 @@ method.restore = function restoreMocks() {
2932
if (!m.exist) {
3033
delete m.obj[m.key];
3134
} else {
32-
m.obj[m.key] = m.original;
35+
Object.defineProperty(m.obj, m.key, m.descriptor);
3336
}
3437
}
3538
mocks = [];

test/method-test.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
'use strict';
2+
13
var muk = require('..');
24
var assert = require('assert');
35
var fs = require('fs');
@@ -87,6 +89,29 @@ describe('Mock property', function () {
8789
});
8890
});
8991

92+
describe('Mock getter', function() {
93+
var obj = {
94+
get a() {
95+
return 1;
96+
}
97+
};
98+
99+
it('Contains original getter', function() {
100+
assert.equal(obj.a, 1, 'property a of obj is 1');
101+
});
102+
103+
it('Methods are new getter after mocked', function() {
104+
muk(obj, 'a', 2);
105+
assert.equal(obj.a, 2, 'property a of obj is equal to mock');
106+
});
107+
108+
it('Should have original getter after muk.restore()', function() {
109+
muk(obj, 'a', 2);
110+
muk.restore();
111+
assert.equal(obj.a, 1, 'property a of obj is equal to mock');
112+
});
113+
});
114+
90115
function hasOwnProperty(obj, prop) {
91116
return Object.prototype.hasOwnProperty.call(obj, prop);
92117
}

0 commit comments

Comments
 (0)