Skip to content

Instantly share code, notes, and snippets.

@mmanela
Created July 19, 2012 20:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmanela/3146690 to your computer and use it in GitHub Desktop.
Save mmanela/3146690 to your computer and use it in GitHub Desktop.
Simple JavaScript stubbing function
function stub() {
return {
of : function (name, callback, returnValue) {
this[name] = function () {
var args = Array.prototype.slice.call(arguments);
this[name].calls.push(args);
var ret = null;
if(callback)
ret = callback.apply(this, args);
if(returnValue) return returnValue;
return ret;
};
this[name].calls = [];
return this;
}
};
}
function renderBlueSquareAndTranslate(height,width, context) {
context.fillStyle = "#0000FF";
context.translate(50,0);
context.fillRect(0,0,height,width);
}
test("will render blue square and translate right 50px", function() {
var context = stub().of("fillRect")
.of("translate");
renderBlueSquareAndTranslate(10,10, context);
equal(context.fillRect.calls.length, 1);
equal(context.translate.calls[0][0], 50);
equal(context.translate.calls[0][1], 0);
equal(context.fillStyle, "#0000FF");
});
test("will capture call arguments for multiple calls", function() {
var s = stub().of("action");
s.action("matt",8);
s.action("mal",4);
equal(s.action.calls.length,2);
equal(s.action.calls[0][0],"matt");
equal(s.action.calls[0][1],8);
equal(s.action.calls[1][0],"mal");
equal(s.action.calls[1][1],4);
});
test("will invoke callback with arguments", function() {
var arg0, arg1;
var callback = function() { arg0 = arguments[0]; arg1 = arguments[1]; return 10;};
var s = stub().of("action", callback);
var res = s.action("matt", 8);
equal(arg0,"matt");
equal(arg1,8);
equal(res,10);
});
test("will use returnVal over return value of callback", function() {
var arg0, arg1;
var callback = function() { arg0 = arguments[0]; arg1 = arguments[1]; return 5;};
var s = stub().of("action", callback, 10);
var res = s.action("matt", 8);
equal(res,10);
});
test("will stub multiple methods and test only one is called", function() {
var s = stub().of("action").of("other");
s.action();
equal(s.action.calls.length,1);
equal(s.other.calls.length,0);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment