Archive

Posts Tagged ‘mock objects’

JavaScript Mock Objects

December 23rd, 2009

While testing a library I’m writing I found that I needed to pass in a simple mock object with a small set of methods and track how many times and with what values each of the methods gets called.

The following snippet of code is what I came up with.

function mock() {
    var mockMethods = arguments;
 
    var dummy = {}
    dummy.calls = [];
 
    for (var i=0; i< mockMethods.length; i++) {
        var methodName = mockMethods[i];
        dummy.calls[methodName] = [];
        dummy[methodName] = (function(methodName) {
            return function() {
                //Convert function arguments into an array
                var args = [];
                for (var i=0; i<arguments.length; i++) 
                    args[i] = arguments[i];
 
                this.calls[methodName].push(args);               
            }
        })(methodName);
    }
 
     return dummy;
}

And in an qunit test I’d use it like this:

test("fills rect when bounds and fillStyle are good", function() {
    var n = new PNode({
        bounds: new PBounds(0, 0, 20, 20),
        fillStyle: "rgb(255,0,0)"
    });
 
    var mockCtx = mock("fillRect");
    n.paint(mockCtx);
 
    same(mockCtx.calls.fillRect[0], [0,0,20,20]);
})

I hope someone finds this useful.

Agile Development, JavaScript , , ,