Skip to content

Commit

Permalink
Support an object property function
Browse files Browse the repository at this point in the history
  • Loading branch information
koba04 committed Nov 6, 2017
1 parent b2cc619 commit 368899a
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 13 deletions.
30 changes: 21 additions & 9 deletions packages/enzyme-test-suite/test/Utils-spec.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -555,15 +555,27 @@ describe('Utils', () => {
return this.count;
}
}
const counter = new Counter();
const original = counter.incrementAndGet;
const spy = spyMethod(counter, 'incrementAndGet');
counter.incrementAndGet();
counter.incrementAndGet();
expect(spy.lastReturnValue).to.equal(3);
spy.restore();
expect(counter.incrementAndGet).to.equal(original);
expect(counter.incrementAndGet()).to.equal(4);
const instance = new Counter();
const obj = {
count: 1,
incrementAndGet() {
this.count = this.count + 1;
return this.count;
},
};

// test an instance method and an object property function
const targets = [instance, obj];
targets.forEach((target) => {
const original = target.incrementAndGet;
const spy = spyMethod(target, 'incrementAndGet');
target.incrementAndGet();
target.incrementAndGet();
expect(spy.lastReturnValue).to.equal(3);
spy.restore();
expect(target.incrementAndGet).to.equal(original);
expect(target.incrementAndGet()).to.equal(4);
});
});
});
});
16 changes: 12 additions & 4 deletions packages/enzyme/src/Utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -269,20 +269,28 @@ export function cloneElement(adapter, el, props) {

export function spyMethod(instance, methodName) {
let lastReturnValue;
const originalMethod = instance[methodName];
const hasOwn = Object.hasOwnProperty.call(instance, methodName);
Object.defineProperty(instance, methodName, {
configurable: true,
enumerable: false,
value(...args) {
const result = this.constructor.prototype[methodName].apply(this, args);
const result = originalMethod.apply(this, args);
lastReturnValue = result;
return result;
},
});
return {
restore() {
/* eslint-disable no-param-reassign */
delete instance[methodName];
/* eslint-enable no-param-reassign */
if (hasOwn) {
/* eslint-disable no-param-reassign */
instance[methodName] = originalMethod;
/* eslint-enable no-param-reassign */
} else {
/* eslint-disable no-param-reassign */
delete instance[methodName];
/* eslint-enable no-param-reassign */
}
},
get lastReturnValue() {
return lastReturnValue;
Expand Down

0 comments on commit 368899a

Please sign in to comment.