Testing Tip: The Dummy Function

Sometimes when you are writing tests, you find yourself testing whether a particular callback has been called. For example, you might write a test like this

var lastCalledWithfunction
callback(e){
    lastCalledWith = e
}
obj.bind('someevent', callback)
obj.doSomethingThatShouldTriggerEvent()
expect(lastCalledWith.type).toBe('someevent') // check that callback was called

This is slightly tedious and the code ungainly because you need to introduce a variable in your test, and store the arguments to it so that you can check the result. We can do better

function $dummy(){
    arguments.callee.lastCalledWith = arguments
}
obj.bind('someevent', $dummy)
obj.doSomethingThatShouldTriggerEvent()
expect($dummy.lastCalledWith[0].type).toBe('someevent')

This is a nice and generic, but we have to reset the lastCalledWith attribute before each test, something like

delete $dummy.lastCalledWith

But let's make it more painless

$dummy.reset()

By adding this reset function

$dummy.reset = function(){
    delete this.lastCalledWith
    return this
}

Moreover, reset returns back the dummy function itself, so, now you can write the test like so

obj.bind('someevent', $dummy.reset())
obj.doSomethingThatShouldTriggerEvent()
expect($dummy.lastCalledWith[0].type).toBe('someevent')

Very nice. I like.

blog comments powered by Disqus