diff --git a/lib/sinon/sandbox.js b/lib/sinon/sandbox.js index 8a9123b5e..9d2bc007f 100644 --- a/lib/sinon/sandbox.js +++ b/lib/sinon/sandbox.js @@ -51,11 +51,18 @@ function Sandbox() { return fakeRestorers; }; - sandbox.createStubInstance = function createStubInstance(constructor) { - if (typeof constructor !== "function") { - throw new TypeError("The constructor should be a function."); - } - return this.stub(Object.create(constructor.prototype)); + sandbox.createStubInstance = function createStubInstance() { + var stubbed = sinonStub.createStubInstance.apply(null, arguments); + + var ownMethods = collectOwnMethods(stubbed); + + forEach(ownMethods, function(method) { + push(collection, method); + }); + + usePromiseLibrary(promiseLib, ownMethods); + + return stubbed; }; sandbox.inject = function inject(obj) { diff --git a/test/sandbox-test.js b/test/sandbox-test.js index e8716521b..d8ddb7639 100644 --- a/test/sandbox-test.js +++ b/test/sandbox-test.js @@ -280,6 +280,71 @@ describe("Sandbox", function() { }); } }); + + it("allows providing optional overrides", function() { + var Class = function() { + return; + }; + Class.prototype.method = function() { + return; + }; + + var stub = this.sandbox.createStubInstance(Class, { + method: sinonStub().returns(3) + }); + + assert.equals(3, stub.method()); + }); + + it("allows providing optional returned values", function() { + var Class = function() { + return; + }; + Class.prototype.method = function() { + return; + }; + + var stub = this.sandbox.createStubInstance(Class, { + method: 3 + }); + + assert.equals(3, stub.method()); + }); + + it("allows providing null as a return value", function() { + var Class = function() { + return; + }; + Class.prototype.method = function() { + return; + }; + + var stub = this.sandbox.createStubInstance(Class, { + method: null + }); + + assert.equals(null, stub.method()); + }); + + it("throws an exception when trying to override non-existing property", function() { + var Class = function() { + return; + }; + Class.prototype.method = function() { + return; + }; + + var sandbox = this.sandbox; + + assert.exception( + function() { + sandbox.createStubInstance(Class, { + foo: sinonStub().returns(3) + }); + }, + { message: "Cannot stub foo. Property does not exist!" } + ); + }); }); describe(".stub", function() {