Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ


Choose your language

InfoQ Homepage News Article: JavaScript Test Driven Development with JsUnit and JSMock

Article: JavaScript Test Driven Development with JsUnit and JSMock

This article by Dennis Byrne is a crash course in writing maintainable JavaScript. Dennis adds features to a running example by iteratively following a simple principle: write a unit test, make it pass. Each test serves as a quality feedback loop, creating both a safety net and an executable form of documentation for anyone who wants to change the production code. By starting each feature with a simple failing test he ensures that all features are tested. He avoids the cost of rewriting code to test it later. This is particularly valuable given the fact that JavaScript developers have so much rope to hang themselves with - consider how much global mutable state there is between the DOM API and the language itself.

Our running example is a casino slot machine with three reels.  Each reel has five possible states, represented by images.  Each reel randomly assumes a state when the play button of the slot machine is pressed. The slot machine balance will be incremented or decremented depending on whether or not all three reel states are equal.

Our tools will be stubs, mock objects and a little bit of dependency injection. We will use JsUnit to run unit tests and a JavaScript mock object library called JsMock. Integration testing, a compliment of unit testing, is beyond the scope of this article. This does not mean integration testing is less important - just that we will strive for quick feedback rather than the slower and more comprehensive feedback obtained with tools like Selenium and Watir.

Read the full article here: JavaScript Test Driven Development with JsUnit and JSMock

Rate this Article