We're hiring!

We're actively seeking developers & designers for our new Detroit location. Learn more

JSMock – a mock object library for JavaScript

There are a growing number of developers doing TDD with JavaScript which is why unit testing frameworks like JsUnit exist for it. Sadly though, while many languages have had mock object libraries for years, JavaScript has had none. Hence the birth of JSMock, a mock object library I wrote for JavaScript that fills the ‘mock object’ void in JavaScript Test Driven Development.

JSMock’s interface is fairly straightforward. Record the expectations, play them back, and then verify that the expectations of the mock(s) have been met. The default and only behavior of JSMock is strict ordering for each mock across mocks from a particular ‘MockControl’.

Here is a fairly simple example:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 
function Transmission() {   this.applyClutch = function() {// code // }   this.disengageClutch = function() { // code // }   this.shiftTo = function() { // code // }  }  var mockControl = new MockControl(); var transmissionMock = mockControl.createMock(Transmission);  transmissionMock.expects().applyClutch(); transmissionMock.expects().shiftTo(1); transmissionMock.expects().disengageClutch();  var vehicle = new Vehicle(transmissionMock); vehicle.shiftTo(1);  mockControl.verify()

JSMock also has support for constraints via the TypeOf object. For example if an anonymous function is passed in as an argument, TypeOf can be used to assert that a function type was passed in ( TypeOf.isA(Function) ). However, if a constraint is used it should probably be in conjunction with andStub in order to better test what was passed in.

1 2 3 4 5 6 
var capturedBlock = null; iteratorMock.expects().select(TypeOf.isA(Function)).andStub(function(block) {   capturedBlock = block; });  assertTrue(block.call("elementInList"));

Other examples of JSMock usage can be found here. There is also an article on Ajaxian that has a somewhat realistic example of how to test JavaScript using JSMock.

This entry was posted in Testing, Tools. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Marguerite Lindsay
    Posted January 20, 2007 at 3:26 pm

    k6eexnbq4lq1lml9

  2. Glenna Parsons
    Posted January 20, 2007 at 3:26 pm

    mleqy820ixewxeup

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">