Skip to content

Commit

Permalink
Use has package and getOwnPropertyDescriptor
Browse files Browse the repository at this point in the history
  • Loading branch information
koba04 committed Oct 18, 2017
1 parent 20b6ece commit 4103c0e
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 4 deletions.
13 changes: 13 additions & 0 deletions packages/enzyme-test-suite/test/Utils-spec.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -576,5 +576,18 @@ describe('Utils', () => {
expect(target.incrementAndGet()).to.equal(4);
});
});
it('should be able to restore the property descriptor', () => {
const obj = {};
const descriptor = {
configurable: true,
enumerable: true,
writable: true,
value: () => {},
};
Object.defineProperty(obj, 'method', descriptor);
const spy = spyMethod(obj, 'method');
spy.restore();
expect(Object.getOwnPropertyDescriptor(obj, 'method')).to.deep.equal(descriptor);
});
});
});
1 change: 1 addition & 0 deletions packages/enzyme/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"dependencies": {
"cheerio": "^1.0.0-rc.2",
"function.prototype.name": "^1.0.3",
"has": "^1.0.1",
"is-subset": "^0.1.1",
"lodash": "^4.17.4",
"object-is": "^1.0.1",
Expand Down
17 changes: 13 additions & 4 deletions packages/enzyme/src/Utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import isEqual from 'lodash/isEqual';
import is from 'object-is';
import entries from 'object.entries';
import functionName from 'function.prototype.name';
import has from 'has';
import configuration from './configuration';
import validateAdapter from './validateAdapter';

Expand Down Expand Up @@ -270,7 +271,11 @@ export function cloneElement(adapter, el, props) {
export function spyMethod(instance, methodName) {
let lastReturnValue;
const originalMethod = instance[methodName];
const hasOwn = Object.hasOwnProperty.call(instance, methodName);
const hasOwn = has(instance, methodName);
let descriptor;
if (hasOwn) {
descriptor = Object.getOwnPropertyDescriptor(instance, methodName);
}
Object.defineProperty(instance, methodName, {
configurable: true,
enumerable: false,
Expand All @@ -283,9 +288,13 @@ export function spyMethod(instance, methodName) {
return {
restore() {
if (hasOwn) {
/* eslint-disable no-param-reassign */
instance[methodName] = originalMethod;
/* eslint-enable no-param-reassign */
if (descriptor) {
Object.defineProperty(instance, methodName, descriptor);
} else {
/* eslint-disable no-param-reassign */
instance[methodName] = originalMethod;
/* eslint-enable no-param-reassign */
}
} else {
/* eslint-disable no-param-reassign */
delete instance[methodName];
Expand Down

0 comments on commit 4103c0e

Please sign in to comment.