Alex headshot

AlBlue’s Blog

Macs, Modularity and More

Testing AJAX applications

2006 Test

Joe Walnes and Adam Connors gave a presentation talking about testing AJAX applications. The principle was that if your AJAX application is one large JavaScript function, it's not easily testable. Therefore, if you refactor (manually -- unless there are AJAX refactoring tools availalble?), so that the AJAX exhibits more of a Model-View-Controller model (or, in Struts terminology "Model2", largely because "Model1" wasn't MVC...). In fact, splitting the application up into a separate Model-View-Controller component can also result in the JavaScript source files into separate files (e.g. view.js,controller.js and model.js.)

Of course, the goal in this is to split apart the code that's doing back-end processing (e.g. firing/requesting new DOM data via XmlHttpRequest) versus interacting with events that the user is doing. You can thus test individual parts separately -- the view isn't easily testable (thus, you have to do it manually) but you can check that the events are being fired appropriately at the right places, and that the controller is returning the right data.

So, having split the code up into its own units, you can start driving it with JavaScript test cases e.g. jsUnit. You can also set up mock objects to ensure that the appropriate entries are invoked on the controller etc. Pretty much, this is all going over the basics that have been done in other applications/languages before (e.g. JUnit/Java) and so applying it to JavaScript and AJAX applications is a natural evolution from this. Perhaps it's an interesting focus because to date, AJAX applications have just been huge functions in a single JavaScript file; and that people who are doing AJAX applications haven't yet thought about how to test them.

There are asynchronous issues that can play in AJAX though; and it's possible to get race conditions fairly easily. It's somewhat more difficult to get a decent test harness that will test various asynchronous testing; but then again, testing asynchronous code in a multi-threaded language like Java is actually fairly hairy too.

The nice thing about this example is that they've actually got a decent JavaScript-type green test bar that goes green when all tests are run, using JSUnit. (Plus, since it's in JavaScript, it runs in the browser and updates it on the fly as tests are run.) Mind you, something like GWT might still be a better way of getting bug-free AJAX code. After all, languages are getting higher and higher; for example, everything is written in a high-level language (Java) which sits on a VM (in C) which is compiled to assembly. Just because you can write at lower levels, doesn't mean that it makes sense; and I think that JavaScript is just one of those byte-code type technologies, which can be compiled into, but don't make sense as a high-level language to write in the first place. The video is now available.