Dead simple stubbing for JavaScript

I’m writing a lot of JavaScript these days, and for testing I mostly use QUnit. When I need to quickly stub a piece of the code that I’m testing, I like to use the following micro-library. What it does is enable you to replace a bunch of methods on an object with stub versions, in a easily reversible way.

I use RequireJS, but if you don’t, just remove the define and outer function.

define(function() {
    var stub = function(obj, stubs) {
        obj._stubbed = obj._stubbed || {};
        for (var name in stubs) {
            obj._stubbed[name] = obj[name];
            obj[name] = stubs[name];
    stub.restore = function(obj) {
        if (!obj || !obj._stubbed) return;
        for (var name in obj._stubbed) {
            obj[name] = obj._stubbed[name];
        delete obj._stubbed;
    return stub;

Here is how you would replace two methods bar and baz on an object foo:

stub(foo, {
    bar: function() {
        return "stubbed bar";
    baz: function(glop) {
        return "stubbed baz " + glop;

And here is how you can put everything back in place once you’re done:


I hope this helps...

No Comments