August 17th 2011

BDD for JavaScript with Jasmine

Both peepcode and tekpub have done excellent screencasts on using backbone.js in the last couple of months. In peepcode’s screencasts, they used a JavaScript BDD framework that was very intriguing called Jasmine.

From the Jasmine home page:

Jasmine is a behavior-driven development framework for testing your JavaScript code. It does not depend on any other JavaScript frameworks. It does not require a DOM. And it has a clean, obvious syntax so that you can easily write tests.

Here is a non trivial example of some specs I wrote for a recent enhancement request.

The example above uses a handy plugin for the fixtures called jasmine-jquery. One gotcha to look out for when using the fixtures is that current versions of chrome do not allow file:// URI without an override. You can start Chrome with the —allow-file-access-from-files condition to get around this.

One other plugin that comes in handy when using Jasmine (though not used in the example above) is Sinon. Sinon provides standalone test spies, stubs and mocks for JavaScript. It has no dependencies, and works with any unit testing framework.