March 1, 2015 · Programming Testing ·

Testing async code with mocha basics

I've learned quite a few things during my time at Groupon so far. Writing test code that can hook into your Node.js application is one of them. I initially started writing test code using Mocha, assuming it would respond in a traditional sync-way. I was extremely mistaken.

The mistake:

So if I called a function that had to go make a HTTP call to a mock server, then I reference that function in my test code, call it and wait. The mistake here is that your test code will not wait. The mocha expect function will execute before the HTTP callback is executed! We do not want this!

The solution:

done() is the solution. Provide it in your callback. It tells Mocha that you have async test code and you need to wait. It technically tells Mocha to enter a timer and wait a certain time period for the async code to complete before it runs the validation check methods like expect, etc...

I wrote an example of how to use the done() function within your test code in both Javascript(left) and Coffeescript(right).

Hope that helps fellow Node.js testers!

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket
Comments powered by Disqus