Skip to content

Commit

Permalink
Refactor; introduce sinon.wrapMethod to handle wrapping of methods on…
Browse files Browse the repository at this point in the history
… object with a restore() option
  • Loading branch information
cjohansen authored and Christian Johansen committed Mar 30, 2010
1 parent 0feec9f commit 7fb6657
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 19 deletions.
29 changes: 28 additions & 1 deletion src/sinon.js
@@ -1,3 +1,30 @@
var sinon = (function () {
return {};
function wrapMethod (object, property, method) {
if (!object) {
throw new TypeError("Should wrap property of object");
}

if (typeof method != "function") {
throw new TypeError("Method wrapper should be function");
}

var wrappedMethod = object[property];
var type = typeof wrappedMethod;

if (!!wrappedMethod && type != "function") {
throw new TypeError("Attempted to wrap " + type + " as function");
}

object[property] = method;

method.restore = function () {
object[property] = wrappedMethod;
};

return method;
}

return {
wrapMethod: wrapMethod
};
}());
5 changes: 5 additions & 0 deletions src/spy.js
@@ -1,4 +1,9 @@
(function () {
function stub (object, property) {
var method = object[property];
return sinon.wrapMethod(object, property, spy.create(method));
}

function spy (func) {
return spy.create(func);
}
Expand Down
23 changes: 5 additions & 18 deletions src/stub.js
@@ -1,31 +1,18 @@
(function () {
function stub (object, property, func) {
if (!object) {
throw new TypeError("Should stub property of object");
}

if (!!func && typeof func != "function") {
throw new TypeError("Custom stub should be function");
}

var method = object[property];
var type = typeof method;

if (!!method && type != "function") {
throw new TypeError("Attempted to stub " + type + " as function");
}
var wrapper;

if (typeof func == "function") {
object[property] = !!sinon.spy ? sinon.spy(func) : func;
if (func) {
wrapper = !!sinon.spy ? sinon.spy(func) : func;
} else {
object[property] = stub.create();
wrapper = stub.create();
}

object[property].restore = function () {
object[property] = method;
};

return object[property];
return sinon.wrapMethod(object, property, wrapper);
}

Object.extend(stub, (function () {
Expand Down

0 comments on commit 7fb6657

Please sign in to comment.