Tools for Tests (JavaScript Edition)
In my previous article Tools for tests, I discussed tools designed to help write better quality tests. This article expands on the topic by exploring several tools and libraries that help test JavaScript.
Testing JavaScript seems unnatural on the surface, because it’s difficult to see how it can be automated. Tests require a full implementation of the DOM, so it’s hard to imagine how anything but browser–based tests could be useful. Luckily, most operating systems provide some way of accessing applications in a scriptable fashion — AppleScript in Mac OS is the most obvious example. So before you start using alert() to print values and debug code consider this: automating JavaScript testing is definitely possible and you have no excuse for not doing it.
Code design
Well–designed code is often easy to test. If you write JavaScript inline with your HTML you’re going to have a hard time testing it.
The first step beyond inlining JavaScript is to use classes to bundle functionality, then using simple inline hooks to trigger them. This is generally how the Ruby on Rails JavaScript helpers work with scriptaculous. Have a look at the Prototype API documentation to see how to construct classes if you haven’t done this before.
I prefer a less intrusive approach. I use classes to model things that have the potential get reused in different instances, and Object to group methods that trigger these "models."
- “Static” concepts that get reused make good classes — anything generic that can appear in different places
- Code used to instantiate classes can be grouped together by topic in a hash or
Object - $$() is useful for iterating over elements with a particular CSS selector and applying events to them
JavaScript architectural approaches could take up another article. Just remember that if your JavaScript isn’t easy to test, it might need work.
- JSUnit
- unittest.js from scriptaculous
- Firebug
- JSLint
- Rhino