Friday, October 12th, 2007
Testing JavaScript Objects with Function.prototype.call and Crosscheck
<p>Jason Harwig has written a quick tip on Testing JavaScript Objects with Function.prototype.call. The example that he uses is:-
-
/**
-
* Call a function with the given execution context and parameters.
-
* @param <object> instance the object to use as the "this" inside the function
-
* @param <array of Objects> parameters the objects to pass to the function
-
*/
-
Function.prototype.call(instance, parameters...);
-
-
var x = { message: 'Hello World' };
-
var hello_function = function(name) {
-
alert(this.message + ", " + name);
-
}
-
hello_function.call(x, 'jason');
-
In the context of Crosscheck, the JavaScript unit testing framework, you would see this work via:
-
-
// 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 ');
-
}
-
What is Crosscheck?
Crosscheck is an open source testing framework for verifying your in-browser javascript. It helps you ensure that your code will run in many different browsers such as Internet Explorer and Firefox, but without needing installations of those browsers. The only thing you need is a Java Virtual Machine.
Related Content:











I have also added a simple testing method, known from python as DocTest as a patch to dojo (should be easy to adapt to other frameworks). You can find it here http://trac.dojotoolkit.org/ticket/4651 its still only a ticket for dojo.
wolfram
It’s good to write tests, of course, but I don’t see what Function.prototype.call() brings to the party.
This code:
assertTrim: function() {
assertEquals('text', String.prototype.trim.call(' text') );
assertEquals('text', String.prototype.trim.call(' text \n ') );
}
could be written:
assertTrim: function() {
assert( ' text'.trim() == 'text' );
assert( ' text \n '.trim.call() == 'text' );
}
That seems much more straightforward and to the point. It uses method calls that look like the real thing (because they are), and it should be just as fast as the more lengthy version.
If I missed something here, I’d be grateful to anyone who could set me straight. Thanks!
Typo in my comment above. The second version should read:
assertTrim: function() {
assert( ' text'.trim() == 'text' );
assert( ' text \n '.trim() == 'text' );
}
Short and sweet!
Michael,
I agree that the string case is one where there isn’t any benefit to using call, but with a custom object that did many things in the constructor would make testing easier.
As I stated in the blog, the object I was testing did a lot of DOM scripting in the constructor and I didn’t care to mock that in every instance function test.
i have one site with a lot of ajaxscript. Mabey it is usefull for the readers of this blog.
http://scripts.ajaxflakes.com/