Near Infinity

Testing JavaScript Objects with Function.prototype.call

By Jason Harwig

Oct 11, 2007

This is a short tip that I found useful for testing complex JavaScript objects using crosscheck. For more information on crosscheck see my article on JavaScript Unit Testing with Crosscheck.

Testing instance methods can be a pain if the functions use instance variables and the object is heavyweight. In my case the constructor did a lot with the DOM that I didn't want to mock. Instead of invoking the function through an instance of an object, I called it statically.

Function.call

"call" is a built in function on the function prototype in JavaScript -- just a little confusing :). Using function.call we can invoke functions and pass in an object with properties that the function depends on. Here is an example documentation of the function, and an example use case.
Function.prototype.call(instance, parameters...); var x = { message: 'Hello World' }; var hello_function = function(name) { alert(this.message + ", " + name); } hello_function.call(x, 'jason');

Crosscheck and call

To test an instance function in crosscheck, set the object to values you want the function to get and use call to invoke it. Here is an example function and test.
// function to test String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,''); } // crosscheck test assertTrim: function() { assertEquals('text', String.prototype.trim.call(' text'); assertEquals('text', String.prototype.trim.call(' text \n '); }

Keep increasing that coverage!