Monday, January 18, 2010

Unit Testing For Javascript

Recently I had to write some fairly substantial javascript, and in the process I was reminded of how fast javascript, like most scripting languages, and get out of hand really quick. I took a step back and thought why should I work in javascript any different then I do in other language? Just because it’s a scripting language doesn't make it any less valid of a development platform, and I can apply the same design pattern and principles I would with anything else.

So The first thing I did was went looking for a unit testing framework and I found JSUnit. JSUnit is available from http://www.jsunit.net/ and is a port of the JUnit framework to javascript. The entire testing framework and test runner is written in javascript so I can use it anywhere you use javascript and in any development platform(php, ruby, Perl, java, .net, etc).

Getting started I have this javascript function I want to test

   1: function addTwoNumber(x, y) {
   2:     var result = x + y;
   3:     return result;
   4: }

so first I create an html page and add the jsUnitCore.js and my .js file containing this function (almost all of your javascript really should be in .js files for a number of reasons, but that’s another blog post).

   1: <html>
   2:     <head>
   3:         <script language="JavaScript" src="jsUnitCore.js"></script>
   4:         <script language="JavaScript" src="javascriptCode.js"></script>
   5:     </head>
   6:     <body>        
   7:     </body>
   8: </html>

then to add test cases I create functions inside a script tag in the body of the html page like so

   1: <body>
   2:     <script type="text/javascript">
   3:         function test_addTwoNumber_TwoNumbersAreAdded() {
   4:             var result = addTwoNumber(2, 2);
   5:             assertEquals("Adds 2 values together", 4, result);
   6:         }
   7:  
   8:     </script>
   9: </body>
to tag a function as a test, simply start the function off with the text “test” and the test runner will pick it up and run it. The assert is done with the function assertEquals provided by the jsUnitCore.js file and takes 3 prams (test description, expected value, and actual result) and to run the test you simply open the testRunner.html page in the jsunit dir in a browser

image

then add the file location and run the tests, it’s that simple. If you look at the screen shot you will notice that I’m using opera, for what ever reason I couldn’t get the test runner to work in Firefox, every time I would try and run my test file I would get a time out error, The funny thing is it works in IE, Chrome, and Opera just fine, weird.

No comments: