Luca Grulla

Javascript testing

1 minute read

Javascript has become in the last year the language for rich web applications, but still it rarely receives the level of attention it deserves.

Libraries such jQuery boost our productivity but the code we often end up writing tend to be a big ball of mud, with an entangled mix of presentation logic, busines logic and server side interaction, all incredibly hard to test and to maintain.

It’s time to move away from this approach and start writing better quality Javascript.

The very first step required to avoid Javascript spaghetti code is start thinking to Javascript as a first class language, and start dealing with it with the same mindset and approach we would use for any server side language.

With this new approach in the same way we identify roles and integration points in server side code we want to start building abstractions in our Javascript codebase.

With the right abstractions in place we are defining clear boundaries between different parts of the system, and as a consequence our code is simpler, we promote reuse and the DRY principle, and we are finally enabling better testing.

Let’s look at any standard Web 2.0 Javascript code from this new perspective: now the DOM and HTTP are two clear integration points.

Our javascript code manipulates the DOM adding &nodes or changing existing nodes content in the same way any other language would interact with a database.Each call to a server over HTTP via Ajax is exactly the same of calling a web server from our server side code.

With these very two first abstractions in mind, we can start rewriting our code, isolating these interactions behind clearly defined objects.

Now the javascript code is not a ball of mud anymore, but a network of objects that collaborate. With these smaller objects in place we can now favour interaction based tests, moving away from any dependency on the DOM and on the HTTP protocol.

The identified abstractions let me actually mock and stub things out and test if the different tiers in my javascript code are exchanging the right messages. This separation of concerns keep the business logic nicely isolated from the user interface transformations, enabling also a cleaner state based testing for that specific part of the code (there are no more dependencies on the DOM).