Testing Javascript Headless with QUnit and Phantomjs


Push some code, deploy it, have a beer and cross your fingers. If something breaks, your users will surely use the neat feedback form to report the bug and maybe invite you to their birthdays while they’re at it.


I can’t stress this enough. Testing is important. While your code grows, it gets extremely difficult (and tedious!) to manually test everything.

  • “I’m a rockstar/ninja, my code is rock solid!” – whoops, no payment processing this weekend

  • “just a small fix” –  after partying hard for 8hrs straight @STYLIGHT party

  • “it’s just frontend, man” – crap, where did the navigation go ?

We’ve all been there.

Luckily, unit testing in javascript is a solved problem, there is a plethora of amazing open-source libraries to choose from. We ended up using QUnit as it offers a very clean and simple API, plus it’s used by the jQuery-* projects.

Writing tests with QUnit is pretty straigthforward:

[gist]<a href=”https://gist.github.com/5618427“>https://gist.github.com/5618427</a>[/gist]

More sophisticated and real-world examples can be found in the cookbook.

Now that you wrote your first unit test you probably want to run it. As described in the docs, create a test.html file, include your tests and check the results in the browser. While the result page is pretty cool, opening a browser every time you want to run your tests gets old fast. It’s also not suitable as part of a CI strategy, think jenkins/hudson. The answer is phantomjs.

From the website:

PhantomJS is a headless WebKit scriptable with a JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas and SVG.

Available for linux, osx and even windows it’s a command line tool that coupled with the grunt-qunit plugin makes running your tests a joy. Add a qunit target to your gruntfile and you’re good to go.

[gist]<a href=”https://gist.github.com/5642419“>https://gist.github.com/5642419</a>[/gist] In case  you’re not using grunt (you should!) you can run the testrunner from the console as described here

[gist]<a href=”https://gist.github.com/5642425“>https://gist.github.com/5642425</a>[/gist]

This will run your code w/o opening a browser and spit out debug information and test results to your console. It’s even possible to have the results saved to disk as .xml so your CI dude can play with it. Of course, this assumes your code is written in a testable way. I’d suggest reading up on it here:


Leave A Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.