Testing in QUnit with CoffeeScript

During an interview process recently I was asked to create a CoffeeScript powered AJAX widget for displaying external content. Having never used CoffeeScript before I decided to go about learning it in a completely test driven way instead of the standard of the usual “hack a few things together and recover” way I’ve done in the past.


What is QUnit?

There’s a whole set of JavaScript testing frameworks out there, QUnit is one of the classics. Developed in 2008 as part of jQuery by John Resig it’s since been redeveloped as a standalone and pretty simple to use library.


Unit testing a CoffeeScript class method

Here’s a super basic example of a CoffeeScript class…


Some features of this class

Moving on to the test, in a separate CoffeeScript file use…


Let’s deconstruct this test


Asyncronous assertions

It’s difficult to get very far in a JavaScript application without encountering an Asynchronous method, thankfully with QUnit it’s very easy to test those as well.

Here’s a very simple example of a class with an asynchronous method…

This class has a single method which has a single argument ‘success’ which is called after a 1 second timeout. However if you attempt to test this class using the standard assertions in the previous QUnit you will get an immediate fail so the test must be adapted to be:

Breaking apart this test…


What about multiple Async assertions?

Depending on which school of thought you subscribe to, you may or may not believe multiple assertions in a test are a sign of bad code. Regardless of what you believe here’s how to do multiple Asynchronous assertions…

This test is very similar to the previous test except that in this case there are now two async operations defined. To tell QUnit that there are multiple assertions that must be completed, use the assert.expect method and define how many assertions should be called.