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.


2 Comments
k6eexnbq4lq1lml9
mleqy820ixewxeup