Skip to content

Commit 71be2d4

Browse files
committed
Use has package and getOwnPropertyDescriptor
1 parent eb37d6b commit 71be2d4

File tree

3 files changed

+27
-4
lines changed

3 files changed

+27
-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
@@ -576,5 +576,18 @@ describe('Utils', () => {
576576
expect(target.incrementAndGet()).to.equal(4);
577577
});
578578
});
579+
it('should be able to restore the property descriptor', () => {
580+
const obj = {};
581+
const descriptor = {
582+
configurable: true,
583+
enumerable: true,
584+
writable: true,
585+
value: () => {},
586+
};
587+
Object.defineProperty(obj, 'method', descriptor);
588+
const spy = spyMethod(obj, 'method');
589+
spy.restore();
590+
expect(Object.getOwnPropertyDescriptor(obj, 'method')).to.deep.equal(descriptor);
591+
});
579592
});
580593
});

packages/enzyme/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
"dependencies": {
3434
"cheerio": "^1.0.0-rc.2",
3535
"function.prototype.name": "^1.0.3",
36+
"has": "^1.0.1",
3637
"is-subset": "^0.1.1",
3738
"lodash": "^4.17.4",
3839
"object-is": "^1.0.1",

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

@@ -270,7 +271,11 @@ export function cloneElement(adapter, el, props) {
270271
export function spyMethod(instance, methodName) {
271272
let lastReturnValue;
272273
const originalMethod = instance[methodName];
273-
const hasOwn = Object.hasOwnProperty.call(instance, methodName);
274+
const hasOwn = has(instance, methodName);
275+
let descriptor;
276+
if (hasOwn) {
277+
descriptor = Object.getOwnPropertyDescriptor(instance, methodName);
278+
}
274279
Object.defineProperty(instance, methodName, {
275280
configurable: true,
276281
enumerable: false,
@@ -283,9 +288,13 @@ export function spyMethod(instance, methodName) {
283288
return {
284289
restore() {
285290
if (hasOwn) {
286-
/* eslint-disable no-param-reassign */
287-
instance[methodName] = originalMethod;
288-
/* eslint-enable no-param-reassign */
291+
if (descriptor) {
292+
Object.defineProperty(instance, methodName, descriptor);
293+
} else {
294+
/* eslint-disable no-param-reassign */
295+
instance[methodName] = originalMethod;
296+
/* eslint-enable no-param-reassign */
297+
}
289298
} else {
290299
/* eslint-disable no-param-reassign */
291300
delete instance[methodName];

0 commit comments

Comments
 (0)