Unit testing your JavaScript

Most web developers will agree that unit tests are great, and some even write them…but I know very few developers who write unit tests for their JavaScript, but it’s not really their fault. Most don’t know of good unit test systems for JavaScript and / or don’t write their JavaScript in such a way that you even could test well. This means breaking all the functionality into discreet functions and objects instead of writing old-school procedural crap. There’s also the obvious problem that most of your JavaScript is tied to the browser and the current page. So how do you test stuff in the page? Well, JsUnit lets you do just that and, seeing as I’ve just added a javascript implementation to the FizzBuzz Overthink you can run over and see how to do it for your apps too.

The limitation of JsUnit is that it really wants a complete file to load into the test harness but it’s bean ages since I’ve worked on a site where at least some portion of every page was not dynamically loaded. Fortunately the workaround is fairly simple: grab the source to the JsUnit Test Runner ( testRunner.html ) and extract the form but leave out the the file chooser. Put all that into a template file that will be dynamically loaded into your app when you view the page as a specific test user or with a magic cookie. Otherwise it’s just not there.

Now every page that needs a JavaScript unit test will have a test harness down at the bottom. Click the button and see if it passes. In order to run all the tests on all the pages just have your Selenium tests also check that the unit tests run correctly. Usually you’ll want to have this be a separate test run so that you can log in as the user who gets to see the tests and because you’ll frequently want to populate your forms and such with data that WILL break things just to test that your JavaScript doesn’t blow up in people’s faces.