Unit Testing with JSPM — my sweet setup
JSPM has been a core part of my build process ever since I started out with React. I first fell in love with its automatic deduping when performing its version of npm install. Unfortunately, it still has a few growing pains when performing other tasks like css bundling, deployment, and recently, testing. It’s achievable, but it takes a lot of work to get the out-of-the-box setup to work.
Where does that leave us, then? I took a look at tape and ava, but their support for ES6 source files was lacking. ava does support ES6 in the test files though, so that’s a bonus but still not enough. Furthermore, I import libraries from JSPM in my JSPM code, so these libraries would not be able to find them (they would look in node_modules instead).
Trying my hand at a different approach, I looked for existing JSPM testing solutions out there. My starting point was the official documentation, but the field was pretty bleak.
jspm-mocha-example - An example project that uses Mocha and JSPM.github.com
This one relies on System.import for every test, the asynchronous version of ES6 imports, as apparent by looking at the source of its only test file. To me, this is pretty cumbersome as my code is already written in ES6 imports, and I want to do the same for my test files.
This was another blind alley. After a few hours of figuring out karma configs (especially figuring out when karma was and wasn’t loading my test files through the — log-level debug flag, and the ), I had managed to get a working setup! But then I ran an error when I tried to run the same setup in Ubuntu (I use OSX). The issue seems to have been fixed recently though, so this is still worth trying out. Below is the configuration I got to work .
I had to resort to sed to change the baseURL in config.js to a blank string on the fly, due to yet another compatibility issue.
Eventually, I found a solution revolving around running mocha in the browser, powered by PhantomJS. This is the solution I eventually settled for, and have been happy with it since.
This solution was not without its drawbacks, as there was no way of globbing all my test files out of the box. I later added 2 scripts, one to change the baseURL again, and another to glob all test files. Another problem I couldn’t resolve was that the call to load the generated test file list, as small as it was, could take up to 4 seconds! As a result I have quite a lenient timeout, 10 seconds.
And there you have it! The sweet thing about this set up is that it also allows you to debug in browser just by opening mocha.html.
Another modification I had to make was to call window.initMochaPhantomJS(), due to this issue. By wrapping it in an if check, I also ensure that the test page works in the browser as well.
Additionally, I add mocha and chai to my globals so I have easy access to describe, it, and expect. This could be up to your personal preference though.