Jason Harwig has written a quick tip on Testing JavaScript Objects with Function.prototype.call. The example that he uses is:

JAVASCRIPT:

  1.  
  2. /**
  3. * Call a function with the given execution context and parameters.
  4. * @param <object> instance the object to use as the "this" inside the function
  5. * @param <array of Objects> parameters the objects to pass to the function
  6. */
  7. Function.prototype.call(instance, parameters…);
  8.  
  9. var x = { message: ‘Hello World’ };
  10. var hello_function = function(name) {
  11.   alert(this.message + “, ” + name);
  12. }
  13. hello_function.call(x, ‘jason’);
  14.  

In the context of Crosscheck, the JavaScript unit testing framework, you would see this work via:

JAVASCRIPT:

  1.  
  2. // function to test
  3. String.prototype.trim = function() {
  4.    return this.replace(/^\s+|\s+$/g,”);
  5. }
  6.  
  7. // crosscheck test
  8. assertTrim: function() {
  9.    assertEquals(’text’, String.prototype.trim.call(’  text’);
  10.    assertEquals(’text’, String.prototype.trim.call(’  text  \n ‘);
  11. }
  12.  

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.

Source: Ajaxian
Original Article: http://feeds.feedburner.com/~r/ajaxian/~3/168925981/testing-javascript-objects-with-functionprototypecall-and-crosscheck

Leave a Reply

You must be logged in to post a comment.



Site Navigation