Thursday, March 28, 2024

How Mocha Makes Testing Asynchronous JavaScript Processes Fun

5/20/13

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;   
  beforeEach(function(done){     
     setTimeout(function(){      
       flag = true;       
       
       // complete the async beforeEach      
       done();     
     }, 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(){     
  expect(flag).to.equal(true);
}); 

 

 

 

Conclusion

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.

Rob Gravelle
Rob Gravelle
Rob Gravelle resides in Ottawa, Canada, and has been an IT guru for over 20 years. In that time, Rob has built systems for intelligence-related organizations such as Canada Border Services and various commercial businesses. In his spare time, Rob has become an accomplished music artist with several CDs and digital releases to his credit.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured