From 127ac0a4d4753db88972453c3f7fcea9011ac24e Mon Sep 17 00:00:00 2001 From: Toru Kobayashi Date: Wed, 18 Oct 2017 10:59:30 +0900 Subject: [PATCH] Use has package and getOwnPropertyDescriptor --- packages/enzyme-test-suite/test/Utils-spec.jsx | 13 +++++++++++++ packages/enzyme/src/Utils.js | 17 +++++++++++++---- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/packages/enzyme-test-suite/test/Utils-spec.jsx b/packages/enzyme-test-suite/test/Utils-spec.jsx index 700994281..e44bb1e41 100644 --- a/packages/enzyme-test-suite/test/Utils-spec.jsx +++ b/packages/enzyme-test-suite/test/Utils-spec.jsx @@ -586,5 +586,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); + }); }); }); diff --git a/packages/enzyme/src/Utils.js b/packages/enzyme/src/Utils.js index 673107813..571a64107 100644 --- a/packages/enzyme/src/Utils.js +++ b/packages/enzyme/src/Utils.js @@ -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'; import { childrenOfNode } from './RSTTraversal'; @@ -246,7 +247,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, @@ -259,9 +264,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];