Running mocha tests programatically with JSPM 0.17 beta
Previously, I wrote an article on unit testing with JSPM 0.16.x. It involved a few dead ends, but I did eventually managed to get it to work.
With the upgrade to 0.17-beta though, my old workflow did not work anymore, as mocha-phantomjs threw some errors that I could not debug. I had to look for new solutions again.
After reading this, I decide to focus my efforts on running mocha programatically. The idea of having faster tests without having to simulate a browser appealed to me.
This time, I tried asking for help from the author here and here. With that, I had a faint idea of how to get started. I encountered a few challenges in trying to adapt the basic snippet for my workflow however, and I document them below.
Running tests from multiple files
The original snippet covered the case of running one test file. But to cover multiple test files naively would have involved processing each test file in a loop. It turns out that this actually spawns a separate instance of mocha for each test file, and because of the async nature of file operations, output from each test file got intermixed with each other, also resulting in inexplicable errors.
My solution was to include all the files first, then run mocha at the end.
Working with browser globals
In a perfect world, all my code would be free of global variable tyranny, and have all their dependencies explicitly required. Alas, there are still a few cases where the ease of their use overrides the common argument against them. Examples include the ubiquitous underscore from lodash, $ from jQuery, and this one I can’t help — the window browser global.
My solution was to create to assign all required globals to the global variable in node, and then pass it in mocha’s pre-require hook. I ended up ditching jQuery because I couldn’t get it to execute in a non-browser environment, and rewrote the few functions that relied on it. (goodbye $.isNumeric, hello one-liners!) Testing does help you write better code!
I also added globals for describe, it, expect, and other testing utilities, as documented in my previous post.
Below is my eventual setup:
If anything, I hope this helps you get started on your journey with JSPM 0.17!