Ajax: Tools of the trade

A rich array of tools for the modern JavaScript developer

Where JavaScript developers were once tool-deprived, today we're often overwhelmed with the abundance of options. In this article, Foundations of Ajax author Nathaniel T. Schutta reviews development environments, debuggers, testing tools, and utilities that elevate JavaScript to first-class status in the Web development world. If you're still programming JavaScript in a text editor, this survey of the modern tools landscape should open your eyes -- and could make your life much easier. Level: Beginner

JavaScript is one of today's most widely used -- and misunderstood -- programming languages. Though it has been a part of the Web development toolbox for years, many developers shunned it after struggling with browser incompatibilities and hitting the limits of alerts as a debugging tool. For some time, the solution was a d├ętente: many software engineers retreated to the comfortable confines of the server and left the JavaScript work to user interface designers. But then the earth moved: Jesse James Garrett coined the term Ajax, a new generation of Web applications was born, and developers' interest in JavaScript was renewed.

If you're one of those who've recently returned to the JavaScript fold, you might be surprised to find a rich suite of tools awaiting you. JavaScript programming today entails more than just a text editor and a great deal of patience. In this article I provide you with an overview of the modern JavaScript developer's toolkit, including IDEs that offer code completion, debugging aids that extend beyond alerts, code and UI testing tools, and other helpful utilities.

IDEs

Back in the days of CRT monitors, the humble text editor was the IDE of choice for the JavaScript developer. Unlike the denizens of the back-end, Web developers didn't have fancy editors with autocomplete and refactoring support; no, we had to walk uphill in driving snow. Today though, the story is different. Spurred as much by the rise of dynamic programming languages as by the importance of Ajax, IDEs now support more than just static compiled languages.

NetBeans, IntelliJ, and Eclipse all offer support for JavaScript -- either built-in or through plugins -- that go beyond basic syntax highlighting. Not sure what the arguments are to that library call? Code completion to the rescue! You'll also find error highlighting, debugging, and even refactoring tools. Figure 1 shows a code-completion example in NetBeans.

Figure 1. JavaScript code completion in NetBeans
Figure 1. JavaScript code completion in NetBeans (Click to enlarge.)

IDEs might not give JavaScript developers quite everything they offer the modern Java developer, but we aren't exactly stuck with a magnetized needle either.

Firebug

Web development arguably has two distinct eras: BFB -- the (prehistoric) time before Firebug when we learned the limits of alerts -- and the modern AFB (after Firebug) when we found that we can once again spend quality time with our families. Firebug truly is Web development evolved. Developing a Web application without using Firebug is like coding Java in vi -- it can be done, but it's just not worth the pain.

Firebug is a free, open source Firefox plugin that wraps a number of helpful tools into one incredibly useful package. In addition to a DOM explorer, a CSS tweaker and a network monitor, Firebug gives you:

  • An interactive JavaScript command line where you can quickly try out code
  • The ability to log information to the console
  • Error messages that leave "Object not found" in the dust
  • Full-fledged JavaScript debugging and profiling

Figure 2 shows Firebug in script mode.

Figure 2. Firebug gives you full fledged JavaScript debugging.
Figure 2. Firebug gives you full fledged JavaScript debugging. (Click to enlarge.)

With Firebug at your side, JavaScript development is downright fun!

Firebug Lite

Firebug is amazing, but as a Firefox plugin, it isn't much help when your application goes awry in another browser. There are no options for other browsers as powerful as Firebug (yet), but you can fall back on Firebug Lite to help you get back on track. Firebug Lite not allows you to make the most of Firebug's logging features; it also gives you the error console (including the JavaScript command line); explorers for HTML, CSS and the DOM; and a handy XMLHttpRequest (XHR) viewer.

Although it's no substitute for the real thing, Firebug Lite can be a life saver. You can add it to any page in need of some debugging love, and it's also available as a handy bookmarklet.

YSlow

Are you wondering why your page isn't as snappy as it could be? YSlow to the rescue! A Firebug extension, YSlow gives your page a letter grade based on how well it conforms to a set of performance rules developed by Yahoo!'s Exceptional Performance team. If your page doesn't quite measure up, help is only a click away. YSlow even includes an option to get a printable view of YSlow's data so you can post that coveted A grade on the fridge in the break room. Figure 3 shows a YSlow performance report.

Figure 3. Performance grading with YSlow
Figure 3. Performance grading with YSlow (Click to enlarge.)

But that's not all YSlow can do. In addition to graphically showing you how heavy your pages are (with both an empty and primed cache), YSlow lists all the components on your page, detailing for each the expires date, size, response time, and whether it's gzipped or not. But wait, there's more! Not only does YSlow give you easy access to JSLint (discussed later in this article), but it can also display a "beautified" view of all the JavaScript (or CSS) on the page.

Hammerhead

As you write more JavaScript, performance becomes increasingly important. Although the various browsers continually one-up each other on JavaScript performance benchmarks, gathering performance metrics can be a lifesaver. Hammerhead allows you to load a page repeatedly, giving you readouts on load times based on both empty and primed caches. You can easily export this data for tracking purposes. Keeping an eye on page performance during development can prevent a major issue from cropping up just before release.

Testing JavaScript code

Believe it or not, you can test your JavaScript code. In fact, you have a variety of options at your disposal, depending on whether you prefer test driven development (TDD) or behavior driven development (BDD). Let's examine just a few of the testing frameworks you can use to unit test JavaScript code. I'll get to testing at the UI level in a bit.

JsUnit

Testing code has moved from the realm of best practice to basic professionalism. Today's developers are well-schooled in the use of the various xUnit frameworks available for most programming languages now. JsUnit is a port of JUnit to JavaScript that allows us to test our code in a browser. Instead of a test class, you create a simple HTML test page that includes the JsUnit core file. You write a series of test methods that leverages the JsUnit asserts -- true, false, null, equals, and so on. Just like JUnit, JsUnit provides a setup and a tear-down concept (including a page setup) and you can run a group of related test pages together via a test suite.

JsUnit includes a test runner that gives you the familiar red or green bar. Errors and failures are displayed in a list box -- double clicking reveals the details including the browser's error message. The test runner accepts a number of standard query strings that can change how the runner acts, and you can also pass in your own criteria if you wish. Figure 4 shows the JsUnit TestRunner in action.

Figure 4. The JsUnit TestRunner
Figure 4. The JsUnit TestRunner (Click to enlarge.)

The test runner is great, but how do you incorporate JsUnit tests into your continuous-integration (CI) server? Enter the JsUnit Server, which serves three purposes:

  • Results logging
  • Executing JsUnit tests from Ant or JUnit
  • Executing JsUnit tests on multiple machines (across operating systems and browsers)

Using standard Ant build files, you configure the server with the list of browsers to use, the URL to your test suite, as well as the URLs of the remote machines. Invoking the tests is a simple as calling the appropriate Ant task.

JSSpec

JSSpec brings the world of BDD to JavaScript. Instead of testing by using asserts, you create a set of "specs" that use "shoulds" to test your code. For example, rather than using assertEquals, you'd write should_be. JSSpec includes a before_each and an after_each to house common code across specs. It also has a one-time setup/tear-down concept. If you have code branches for various browsers, your tests can include conditional execution using a set of constants for the various rendering engines or your own custom boolean JavaScript expression. Figure 5 shows the JSSpec runner.

Figure 5. JSSpect brings BDD to JavaScript.
Figure 5. JSSpect brings BDD to JavaScript. (Click to enlarge.)

Though JSSpec is designed to run in a browser, you can run it headless, thanks to some hard work from John Resig and the fine folks at Relevance.

YUI Test

YUI Test is a new entrant to the JavaScript testing world from, as you might guess, Yahoo! Though not a direct port of an xUnit framework, YUI Test will be quite familiar to any test-infected developer. With it, you write tests in a basic Web page that includes the appropriate JavaScript files, using asserts similar to JsUnit's. YUI Test also includes asserts for sameness and data types. As you might expect, it includes setUp and tearDown methods, and you can easily skip tests by using the _should.ignore property.

Unlike the JsUnit and JSSpec, YUI Test allows you to simulate basic user actions such as mouse clicks and key events, and it gives you the ability to pause a test to allow for asynchronous calls to the server. Tests can be grouped using test suites and are run via a basic test runner. Don't judge the runner too harshly -- it's new, and as the tool evolves, it's expected that additional visualizations of the test results will become available.

Crosscheck

Browser quirks and incompatibility are the bane of JavaScript developers. "It works in Firefox" is a common refrain. And although you might be able to run your tests across various operating systems with multiple browsers, maintaining a small server farm isn't trivial (or in some cases possible). All of the testing tools I've discussed thus far ultimately require a browser, and browser testing is notoriously slow. How do we overcome these dueling problems? Crosscheck to the rescue!

Crosscheck runs on the JVM, taking advantage of its ability to run JavaScript. Instead of spawning browsers, Crosscheck tries to simulate the various browser/OS combinations. Because it runs on the JVM and doesn't need to launch browsers, Crosscheck tests are much faster than other options. It also offers a simple automation path, making it a natural for inclusion on your CI box.

Crosscheck is a bit out of date, but if you're struggling with the multi-OS/browser issue, you owe it a chance.

Testing the UI

Unit testing your JavaScript is a good idea, but sometimes -- say in complex Ajax interactions -- you just need to test at the user interface level. This section takes a quick stroll down the UI testing aisle. Although UI tests tend to be slow and somewhat brittle, they can also provide a helpful safety net.

Selenium

Selenium is a Web testing tool from the good people at ThoughtWorks. The Selenium project is broken up into the IDE (a Firefox add-on), Remote Control, and Grid. The IDE, shown in Figure 6, allows you to record an interaction and then either play it back in the default runner or export the test to any of six languages, where you can add them to your preferred testing tool.

Figure 6. The Selenium IDE
Figure 6. The Selenium IDE

Remote Control is a simple server that can launch and kill browsers, allowing you to easily incorporate Selenium tests into your CI server. Grid takes Remote Control to the next level by distributing tests to multiple machines, thus speeding up your test runs.

Watir

Watir is another Web testing tool from ThoughtWorks. This one was written by and for quality-assurance (QA) people. Watir -- short for Web App Testing in Ruby -- allows you to create tests simply and easily using the Ruby language for scripting. Originally it only supported Internet Explorer, but there are now plugins and ports for other browsers and OSs.

YUI Test

Although YUI Test is primarily a unit-testing framework, it does allow some simulations of the DOM and user interaction. Although its capabilities are not as complete as Selenium's or Watir's, it's a viable option, especially if you're already using it to test your JavaScript.

Utilities

A number of tools that don't fit into any particular category are very useful in developing JavaScript. In this section we'll take a look at tools that verify that you aren't committing basic crimes against JavaScript, shrink your code for production, and keep your code well documented.

JSLint

It can be tricky to write good JavaScript. Any number of corner cases can easily slip by if you're not paying attention. Add in the sheer volume of poorly written JavaScript that has been copied and pasted over the years and, well, you get a mess. JSLint examines your code looking for common errors and bad practices. If you follow its advice, you'll have better code when you're done. Your feelings might be hurt in the process, but the final result is worth it. To test your code, you can either cut and paste it into the verifier box (shown in Figure 7) on the JSLint Web site (where you can set a plethora of options) or you can run it from the command line, thanks to Rhino (an open source JavaScript implementation written in Java).

Figure 7. The JSLint verifier
Figure 7. The JSLint verifier (Click to enlarge.)

Minifiers

As we write more and more JavaScript, we can end up with some pretty hefty page weights. And although more and more users are surfing on broadband, we still should minify our JavaScript. A variety of options, including Doug Crockford's JSMin and the YUI Compressor, are available. You may want to try a couple of different options until you settle on the one that works best for your code base and build system. Whichever tool you choose, do shrink your JavaScript before you go to production.

Documentation tools

Documenting your JavaScript can be vital for long-term use and maintenance. You won't find anything as standard as Javadoc, but there are a variety of alternatives. The Prototype library uses PDoc, and YUI uses YUI Doc. You can incorporate either into your world; experiment to see what works best for you.

In conclusion

The state of JavaScript development is strong. No longer are JavaScript developers relegated to alerts and a text editor. Today, we have IDEs with autocomplete, full-fledged debuggers, and a variety of testing tools. JavaScript is a first class citizen in any Web application and today, the JavaScript developers of the world have a top-notch set of tools for crafting world-class interactions.

Nathaniel T. Schutta is a senior software engineer focused on making usable applications. A proponent of polyglot programming, Nate has written two books on Ajax and speaks regularly at various No Fluff Just Stuff symposia, universities, and Java user groups. In addition to his day job, Nate is an adjunct professor at the University of Minnesota, where he teaches students to embrace dynamic languages.

Learn more about this topic

More from JavaWorld

Join the discussion
Be the first to comment on this article. Our Commenting Policies
See more