Skip to content

Commit

Permalink
fix: make it possible to call through to underlying stub in stub inst…
Browse files Browse the repository at this point in the history
…ances

refs #2477
refs #2501
  • Loading branch information
fatso83 committed Mar 24, 2023
1 parent 6e19746 commit 7c42347
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 5 deletions.
8 changes: 3 additions & 5 deletions lib/sinon/stub.js
Expand Up @@ -131,12 +131,10 @@ stub.createStubInstance = function (constructor, overrides) {
throw new TypeError("The constructor should be a function.");
}

// eslint-disable-next-line no-empty-function
const noop = () => {};
const defaultNoOpInstance = Object.create(constructor.prototype);
walkObject((obj, prop) => (obj[prop] = noop), defaultNoOpInstance);
const stubInstance = Object.create(constructor.prototype);
stubInstance[Symbol.for("SinonType")] = "StubInstance";

const stubbedObject = stub(defaultNoOpInstance);
const stubbedObject = stub(stubInstance);

forEach(Object.keys(overrides || {}), function (propertyName) {
if (propertyName in stubbedObject) {
Expand Down
7 changes: 7 additions & 0 deletions lib/sinon/util/core/wrap-method.js
@@ -1,5 +1,7 @@
"use strict";

// eslint-disable-next-line no-empty-function
const noop = () => {};
var getPropertyDescriptor = require("./get-property-descriptor");
var extend = require("./extend");
var hasOwnProperty =
Expand Down Expand Up @@ -230,6 +232,11 @@ module.exports = function wrapMethod(object, property, method) {
}
}
}
if (object[Symbol.for("SinonType")] === "StubInstance") {
// this is simply to avoid errors after restoring if something should
// traverse the object in a cleanup phase, ref #2477
object[property] = noop();
}
}

return method;
Expand Down
17 changes: 17 additions & 0 deletions test/issues/issues-test.js
Expand Up @@ -805,4 +805,21 @@ describe("issues", function () {
assert.isUndefined(restoredPropertyDescriptor);
});
});

describe("#2501 - createStubInstance stubs are not able to call through to the underlying function on the prototype", function () {
it("should be able call through to the underlying function on the prototype", function () {
class Foo {
testMethod() {
this.wasCalled = true;
return 42;
}
}

const fooStubInstance = this.sandbox.createStubInstance(Foo);
fooStubInstance.testMethod.callThrough();
// const fooStubInstance = new Foo()
fooStubInstance.testMethod();
// assert.isTrue(fooStubInstance.wasCalled);
});
});
});

0 comments on commit 7c42347

Please sign in to comment.