How Mocha Makes Testing Asynchronous JavaScript Processes Fun

By Rob Gravelle


I recently wrote an article entitled Test Asynchronous Methods Using the Jasmine runs() and waitFor() Methods. In it, I presented how Jasmine's runs() and waitsfor() methods are utilized in the testing of asynchronous processes. I'm a big fan of Jasmine because of its ease of use and and overall awesomeness. Nonetheless, it isn't perfect. I have heard rumblings about how convoluted the code can become when dealing with successive asynchronous calls. On the same subject, I've also heard how the Mocha Framework has simplified the testing of asynchronous methods. Visionmedia, the makers of Mocha, promise to make "asynchronous testing simple and fun". Sounds like a challenge to me. Let's give it a try and see what's so fun (and not so fun) about the Mocha framework, shall we?

Pain Before the Gain

In the music business, we have an expression called "paying your dues". It's a lot like the Buddhist philosophy that you have to experience pain in order to gain enlightenment (at least I think that's a Buddhist philosophy). Mocha also shares that belief in some ways, because the setup instructions just don't seem that straight-forward to me. It makes use of node's package management (npm) tool. There are also a lot of references to Homebrew, a package manager for OS X.

I was looking around for more installation instruction when I came upon Attila Domokos' Mocha-in-browser project, which facilitates Mocha-based testing in the browser. According to Domokos, Mocha's "browser based tool is deeply buried under its own tests. Extracting it from there takes time and effort." Now, using Mocha in your browser is as easy as downloading the .zip file, extracting it, and opening up the spec/runner.html file in the browser. To use it with your own projects, copy the spec directory into your working directory, reset your JavaScript source and spec files in the spec/runner.html file and you're start to start using it. Needless to say, that's what I'll be doing here today.

Running the Test Demo

The Mocha-in-browser installation includes an index.html file in the public folder that demos the basic functionality of the test framework. The object of the tests is a String Calculator that adds comma-delimited numbers such as "2,3" or "1,2,3". The test runner is contained in the spec folder and is named runner.html. Executing the tests is as simple as opening the runner.html file in a browser, but note that the browser you use seems to have a significant effect on the appearance of the test output. I found that it looked much better in Firefox than in Internet Explorer 9, as the following screen shots show:


StringCalculator Test Output in Internet Explorer:


StringCalculator Test Output in Firefox:


Using Mocha-in-browser On Your Own Projects

So far so good; the framework appears to be super-easy to install and run. But we want to try out its asynchronous method handling. To do that, we need to modify the demo test code to set up an asynchronous process using the setTimeout() function, just like with Jasmine. The only difference is the call to the done() function that tells Mocha that the process has completed. If the process has't come back done or failed an assertion in a certain amount of time (the default is 2000ms), the test fails. This approach negates the need for the waitsFor() method:


function assert(expr, msg) {
  if (!expr) throw new Error(msg || 'failed');

describe("Mocha Ajax Tests", function(){  
  var flag = false;   
       flag = true;       
       // complete the async beforeEach      
     }, 500);   
  it("flag should be true", function(){    
    assert(flag === true);  

Now, I kept things simple by placing the spec in the runner file, but in real world conditions, you would create a separate spec.js file.

Creating Expectations

The Mocha-in-browser is somewhat simplified compared to the full Mocha library, so there isn't much by way of assertion methods. Luckily, a lot of third-party providers have created pluggable assertion systems for Mocha, including should.js, chaijs, and my favorite, expect.js. Just include it in the spec\lib folder, where the mocha.js file resides, add the script reference in your runner page, and you're all set to start using it:

it("flag should be true", function(){     





Well that wasn't to bad at all, I must say, but that can probably be attributed to Domokos' excellent Mocha-in-browser project. Things might get a little hairier once I give Mocha a try in the terminal using node.js. Can't wait.

If you enjoyed this article, please contribute to Rob's rock star aspirations by purchasing one of Rob's cover or original songs from iTunes.com for only 0.99 cents each.

Rob Gravelle resides in Ottawa, Canada, and is the founder of GravelleWebDesign.com. Rob has built systems for Intelligence-related organizations such as Canada Border Services, CSIS as well as for numerous commercial businesses. Email Rob to receive a free estimate on your software project.

In his spare time, Rob has become an accomplished guitar player, and has released several CDs. His former band, Ivory Knight, was rated as one Canada's top hard rock and metal groups by Brave Words magazine (issue #92).

Rob uses and recommends MochaHost, which provides Web Hosting at $3.10 per month, 2 LifeTime Free Domains, and 6 Months Free!

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
Thanks for your registration, follow us on our social networks to keep up-to-date