Jasmine.Async: Making Asynchronous Testing With Jasmine Suck Less
I love Jasmine. It’s a great BDD-style testing framework for browser based JavaScript, and my preferred tool for doing that kind of work. But the asynchronous testing story in Jasmine is painful at best.
Jasmine’s Async Is Painful
Here’s a short example of how you make Jasmine work with asynchronous JavaScript:
This isn’t fun. That “runs” and “waitsFor” code gets repeated all over the place – every time you need to wait for something async to complete. By contrast, look at my previous post on asynchronous testing with Mocha. That simple little “done” function in the beforeEach and it callbacks is so easy to work with. Just add the parameter to the callback, and call “done()” when the async code has completed.
I want Jasmine to work this way, too, because there are things I like about Jasmine vs Mocha and when I use Jasmine, I don’t want to be stuck with horrible async tests. Thus, Jasmine.Async was born out of frustration and little bit of jealousy in how easy it is to do async tests with Mocha.
Jasmine.Async
To use Jasmine.Async, you need to include the jasmine.async.js file in your test suite. In your “describe” functions, create a new instance of the “AsyncSpec” object and pass in the current context (“this”). Now instead of calling “beforeEach”, you can call “async.beforeEach” which gives you a “done” parameter in the callback function, like Mocha does.
There’s an “async.beforeEach”, “async.afterEach” and “async.it” – all of which are given the “done” callback. This is so much more clean and easy to understand now.
So go grab Jasmine.Async and make your async tests suck less.