Awesome FOSS Logo
Discover awesome open source software
Launched 🚀🧑‍🚀

Unit testing with JSPM (SystemJS), mocha and vue.js

Categories

Testing with Mocha and JSPM (and SystemJS)

While vue offers a decent starting point for testing in it’s guide, I found the guide a little lacking in actual how-to. Also, one of my favorite javascript testing tools is mocha, and the specifics on how to integrate it (or jspm for that matter) are not on the site. Of course, it’s not the vue.js team’s job to integrate everyone’s tooling with vue.js, so I took it upon myself to write a little something about it.

tldr; check out the code, but more importantly, check out the second part of this walk through, with a more complete (read: smoothly working) test exmaple:

Multi-part blog post alert

This is a multi-part blog-post!

  1. Part 1 - Unit testing with JSPM, Mocha, and Vue.js
  2. Part 2 - More testing with JSPM, Mocha, and Vue.js
  3. Part 3 - Testing the DOM
  4. Part 4 - Switching from mocha to tape

BONUS Want to see it all working? Check out the gitlab repo with a fully-built example

Back to your regularly scheduled programming

The code

This code is found @ <project>/app/comoponents/alert-notification/component.spec.js

var should = require('should');

// Set up systemjs & JSPM
var Loader = require('jspm').Loader;
var SystemJS = new Loader();

// Define the systemjs path to the component code
var COMPONENT_JS_PATH = 'app/components/alert-notification/component.js';

describe("alert-notification component tests", done => {
  var Component;

    before(done => {
      SystemJS.import(COMPONENT_JS_PATH)
        .then(c => { Component = c; }) // Save component to test-global for later
        .then(done)
        .catch(err => {
          console.log("Error:", err);
          done(err);
        });
    });

    describe("1=1 test", () => {

      it("everything should pass it", () => {
        (1).should.be.equal(1);
      });

    });

});

The comments should be pretty self explanatory, but this is all it actually takes to set up JSPM SystemJS and Mocha and get them all to play nicely in a spec file.

When running Mocha

Due to the naming convention (mocha expects things to be under the test/ directory), When I run my tests I must run them like this:

./node_modules/.bin/mocha app/**/*.spec.js

Of course I have a make target that takes care of that (which I’ll have to update if anything changes of course).

Requirements

Of course, for all this to work, you need to have jspm, mocha, and should installed to NPM. The following commands should take care of that (note JSPM-installing won’t work, since global mocha uses NPM’s packages):

npm install mocha --save-dev npm install should --save-dev

The NPM jspm should already be installed (JSPM installs it)