Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feature] Spy passes through calling with new #1626

Merged
merged 7 commits into from Dec 7, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 12 additions & 4 deletions lib/sinon/spy.js
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
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