QUnit, JavaScript Unit Testing, and TDD

Posted on 26 Mar 2014 by Ty Thorsen

JavaScript unit testing is probably not the sexiest subject imaginable, but as I start to build out thorsent it seems like one worth talking about.

Professionally, for the past six months, I have been working with a team of up to a dozen developers to build a new member portal for a large PBM using the Adobe Experience Manager (CQ5) platform. AEM is a content management system, and by the nature of WCMs, most of the business logic for the components we build is in JavaScript client libraries. Over time, as we rushed to build out functionality and the site became more complex, we realized that we had created some 40,000 lines of interrelated JS and had no good way to test any of it.

After lengthy discussion, my team decided that it would be valuable to implement a unit testing framework for our JavaScript in order to ensure stability going forward. We decided to use QUnit to build out this framework because our application made heavy use of jQuery (QUnit is/was part of the jQuery project and is used to test jQuery itself). To make a long story short, refactoring existing JS to make it unit-testable is a time consuming, and less than enjoyable task. We've made a good start on increasing our test coverage, but still have a long way to go.

The moral of that story is that if you're writing a JavaScript application, or rather an application that utilizes any JavaScript at all, it is worth implementing a unit testing framework from day zero. If test-driven development is your cup of tea, I would highly encourage that as well.

With this in mind, I have created a QUnit framework for thorsent. It's easy to get started. All you need is a JS file, a CSS file, and two particular div elements on a test page and you're well on your way. The QUnit API documentation and cookbook do a good job of laying out and explaining everything else you can do from there. As you can see below, I've written my first test which covers a toggle function for the mobile navigation drawer.

QUnit Screen

I intend to use this framework to do TDD for all future JavaScript development on this site. As easy as it would be to take shortcuts working as a one man team, it is important to commit to best practices such as TDD. Regardless of your team size, being disciplined in these practices will result in cleaner code that has fewer defects and is easier to maintain.

comments powered by Disqus