Monday, March 15, 2010

Javascript unit testing and code coverage

Back in the day, when I earned my crust as a Java developer, I wouldn't dare commit a new change to a code base without some unit tests. Junit and emma proved to be useful tools to make sure that any new additions to a codebase didn't adversely affect existing functionality.

Moving to developing in JavaScript - I guess I got lazy with unit tests. Not having a code coverage tool to let me know which sections of my code were being exercised by test code meant that I didn't have that 'green bar' motivator.

Then I found out about jscoverage. For an example of what this tool can produce, check out their sample reports for dojo. Getting jscoverage up and running on mac can be a bit of a pain though - here's the steps I followed:

1. There's no auto-built dmg for mac, so you have to download and install macports.

2. Once you have that up and running, open a terminal and execute:
sudo port install jscoverage

jscoverage should now be installed on your machine.

3. Check out the jscoverage documentation for examples on how to run jscoverage.

4. I use dojo's doh testing framework to run my tests. If you do too, you need to edit the runner.html file in the doh directory to include the following buton:
<h3 style="margin: 5px 5px 0px 5px; float: left;">D.O.H.: The Dojo Objective Harness</h3>
<button style="margin-top: 5px; float: left;" onclick="window.open('../../jscoverage.html');">Coverage Report</button>
<img src="small_logo.png" height="40" style="margin: 0px 5px 0px 5px; float: right;">

5. All you need to do then is point your browser at whatever file you use to run your dojo tests and you should be all set. Just click on the "Coverage Report" button once your tests have run.

Its that simple ...

No comments:

Post a Comment