Skip to content

Commit 127ac0a

Browse files
committed
Use has package and getOwnPropertyDescriptor
1 parent 3d42977 commit 127ac0a

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

packages/enzyme-test-suite/test/Utils-spec.jsx

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -586,5 +586,18 @@ describe('Utils', () => {
586586
expect(target.incrementAndGet()).to.equal(4);
587587
});
588588
});
589+
it('should be able to restore the property descriptor', () => {
590+
const obj = {};
591+
const descriptor = {
592+
configurable: true,
593+
enumerable: true,
594+
writable: true,
595+
value: () => {},
596+
};
597+
Object.defineProperty(obj, 'method', descriptor);
598+
const spy = spyMethod(obj, 'method');
599+
spy.restore();
600+
expect(Object.getOwnPropertyDescriptor(obj, 'method')).to.deep.equal(descriptor);
601+
});
589602
});
590603
});

packages/enzyme/src/Utils.js

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import isEqual from 'lodash/isEqual';
33
import is from 'object-is';
44
import entries from 'object.entries';
55
import functionName from 'function.prototype.name';
6+
import has from 'has';
67
import configuration from './configuration';
78
import validateAdapter from './validateAdapter';
89
import { childrenOfNode } from './RSTTraversal';
@@ -246,7 +247,11 @@ export function cloneElement(adapter, el, props) {
246247
export function spyMethod(instance, methodName) {
247248
let lastReturnValue;
248249
const originalMethod = instance[methodName];
249-
const hasOwn = Object.hasOwnProperty.call(instance, methodName);
250+
const hasOwn = has(instance, methodName);
251+
let descriptor;
252+
if (hasOwn) {
253+
descriptor = Object.getOwnPropertyDescriptor(instance, methodName);
254+
}
250255
Object.defineProperty(instance, methodName, {
251256
configurable: true,
252257
enumerable: false,
@@ -259,9 +264,13 @@ export function spyMethod(instance, methodName) {
259264
return {
260265
restore() {
261266
if (hasOwn) {
262-
/* eslint-disable no-param-reassign */
263-
instance[methodName] = originalMethod;
264-
/* eslint-enable no-param-reassign */
267+
if (descriptor) {
268+
Object.defineProperty(instance, methodName, descriptor);
269+
} else {
270+
/* eslint-disable no-param-reassign */
271+
instance[methodName] = originalMethod;
272+
/* eslint-enable no-param-reassign */
273+
}
265274
} else {
266275
/* eslint-disable no-param-reassign */
267276
delete instance[methodName];

0 commit comments

Comments
 (0)