Skip to content

Commit

Permalink
Merge pull request sinonjs#224 from telaviv/create-stub-instance
Browse files Browse the repository at this point in the history
wrote sinon.createStubInstance.
  • Loading branch information
cjohansen committed Jan 2, 2013
2 parents 299f208 + 5f200fd commit 44b98e9
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
7 changes: 7 additions & 0 deletions lib/sinon.js
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,13 @@ var sinon = (function (buster) {
}
var string = Object.prototype.toString.call(value);
return string.substring(8, string.length - 1).toLowerCase();
},

createStubInstance: function (constructor) {
if (typeof constructor !== "function") {
throw new TypeError("The constructor should be a function.");
}
return sinon.stub(sinon.create(constructor.prototype));
}
};

Expand Down
61 changes: 61 additions & 0 deletions test/sinon_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -439,5 +439,66 @@ buster.testCase("sinon", {
"returns date": function () {
assert.equals(sinon.typeOf(new Date()), "date");
}
},

".createStubInstance": {
"stubs existing methods": function() {
var Class = function() {};
Class.prototype.method = function() {};

var stub = sinon.createStubInstance(Class);
stub.method.returns(3);
assert.equals(3, stub.method());
},

"doesn't stub fake methods": function() {
var Class = function() {};

var stub = sinon.createStubInstance(Class);
assert.exception(function() {
stub.method.returns(3);
});
},

"doesn't call the constructor": function() {
var Class = function(a, b) {
var c = a + b;
throw c;
};
Class.prototype.method = function() {};

var stub = sinon.createStubInstance(Class);
refute.exception(function() {
stub.method(3);
});
},

"retains non function values": function() {
var TYPE = "some-value";
var Class = function() {}
Class.prototype.type = TYPE;

var stub = sinon.createStubInstance(Class);
assert.equals(TYPE, stub.type);
},

"has no side effects on the prototype": function() {
var proto = {'method': function() {throw 'error'}};
var Class = function() {};
Class.prototype = proto;

var stub = sinon.createStubInstance(Class);
refute.exception(stub.method);
assert.exception(proto.method);
},

"throws exception for non function params": function() {
var types = [{}, 3, 'hi!'];
for (var i = 0; i < types.length; i++) {
assert.exception(function() {
sinon.createStubInstance(types[i]);
});
}
}
}
});

0 comments on commit 44b98e9

Please sign in to comment.