Activate your free membership today | Log-in

Thursday, October 16th, 2008

Jack: Mocking JavaScript the good way

Category: Testing

<p>Jack is a new JavaScript mocking framework coming out of Bekk in Norway. A lot of the RSpec talent is there too, so they know their testing!

Jack features:

  • Set expectations for number of calls and argument constraints
  • Specify mock implementations for specific expectation scenarios
  • Create mock objects with a list of stub functions
  • Reports expectation failures to test frameworks. Currently integrated with JSSpec and Scriptaculous TestRunner

Examples show it off:

JAVASCRIPT:
  1.  
  2. // Expect one call to function
  3. jack(function(){
  4.    jack.expect("jQuery.post").exactly("1 time");
  5.    storeSomething();
  6. });
  7.  
  8. // Expect argument values
  9. jack(function(){
  10.    jack.expect("jQuery.post")
  11.       .exactly("1 time")
  12.       .withArguments("http://example.com/service");
  13.  
  14.    storeSomething();
  15. });
  16.  
  17. // Set other argument constraints
  18. jack(function(){
  19.    jack.expect("jQuery.post")
  20.       .exactly("1 time")
  21.       .whereArgument(0).isOneOf("/serviceOne","/serviceTwo");
  22.  
  23.    storeSomething();
  24. });
  25.  
  26. // Creating a mock object to run expectations against
  27. jack(function(){
  28.    var mockObject = jack.create("mockObject", ['functionOne','functionTwo']);
  29.  
  30.    jack.expect("mockObject.functionOne")
  31.       .exactly("1 time")
  32.       .whereArgument(0).is("something");
  33.  
  34.    mockObject.functionOne("something");
  35. });
  36.  

Related Content:

Posted by Dion Almaer at 9:37 am
1 Comment

++++-
4.2 rating from 34 votes

1 Comment »

Comments feed TrackBack URI

jqMock was my attempt at writing a javascript mock library. It has comprehensive expectation support, with complex argument matching criteria, ordered/unordered expectations, multiplicity control, intercepting return values and throwing exceptions.

Comment by longgoldenears — October 18, 2008

Leave a comment

You must be logged in to post a comment.