Skip to content

Commit

Permalink
Spy passes through calling with new (#1626)
Browse files Browse the repository at this point in the history
This changes the spy behavior so that if the spy is `calledWithNew()` then
the original function will also get called with `new`.

This was throwing an error if you tried spying on an ES6 class object.

fixes #1265
  • Loading branch information
ProLoser authored and fatso83 committed Dec 7, 2017
1 parent 271d84a commit 911c498
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
16 changes: 12 additions & 4 deletions lib/sinon/spy.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ var push = Array.prototype.push;
var slice = Array.prototype.slice;
var filter = Array.prototype.filter;
var ErrorConstructor = Error.prototype.constructor;
var bind = Function.prototype.bind;

var callId = 0;

Expand Down Expand Up @@ -190,11 +191,18 @@ var spyApi = {
try {
this.invoking = true;

returnValue = (this.func || func).apply(thisValue, args);

var thisCall = this.getCall(this.callCount - 1);
if (thisCall.calledWithNew() && typeof returnValue !== "object") {
returnValue = thisValue;

if (thisCall.calledWithNew()) {
// Call through with `new`
// eslint-disable-next-line new-parens
returnValue = new (bind.apply(this.func || func, [thisValue].concat(args)))();

if (typeof returnValue !== "object") {
returnValue = thisValue;
}
} else {
returnValue = (this.func || func).apply(thisValue, args);
}
} catch (e) {
exception = e;
Expand Down
10 changes: 10 additions & 0 deletions test/spy-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,16 @@ describe("spy", function () {
assert(called);
});

it("passes 'new' to underlying function", function () {
function TestClass() {}

var SpyClass = createSpy.create(TestClass);

var instance = new SpyClass();

assert(instance instanceof TestClass);
});

it("passs arguments to function", function () {
var actualArgs;

Expand Down

0 comments on commit 911c498

Please sign in to comment.