Tuesday, May 8, 2012

Running Mocha Specs in the Browser

The way I've been writing JavaScript code might not appeal to other developers: I live my life in the terminal, I write and execute specs in it hitting the browser occasionally just to make sure everything I do works there. Others use the terminal as little as possible. One thing we have in common: we test our JavaScript code with Mocha.

I still remember the cold, autumn day when I first downloaded Jasmine's standalone test-runner a couple of years ago. All I had to do was unzip the file, hook in my own JS source and spec files and I was in business. It even had simple JavaScript objects like Player and Song guiding me through the first steps.

Mocha - unfortunately - does not have a downloadable zip file to help you get started and its browser based tool is deeply buried under its own tests. Extracting it from there takes time and effort.
This writing describes how you can get started with executing your Mocha specs in the browser.

I put all the code of this starter project in a Github repo: mocha-in-browser. You can either clone it or just download the project zip file.

I used the String Calculator Kata as an example. Open up the public/index.html file in your favorite browser and you should see this:

Just type 1,3 in the text box, hit the "Calculate" button and the correct answer appears in green color under the text box.

When you open up the spec/runner.html in the browser, Mocha is happily reporting the test output:

I did not finish the String Calculator Kata. Please work through it not only to sharpen your skills but to get familiar with JavaScript unit testing with Mocha as well.

You can drop the spec directory from this project into your working directory, reset your JavaScript source and spec files in the spec/runner.html file and start using it.

Both Mocha and Should.js are rapidly changing projects. I'd encourage you to download and use the latest source code of those projects as ofter as you can.
I created a Makefile to make this super simple for you. Just run "make" in the project root and you should have the latest version of those files brought to you by node.js and npm.