Server-side testing

The primary target for server-side JavaScript these days is Node.js, but jstest also supports several other platforms, including Narwhal, RingoJS, the PhantomJS scripting runtime, MongoDB, and Windows Script Host.

If you’ve gone through the Getting started and Loading your code tutorials, this article will show you how to run your tests using these server-side platforms.

The tests expect a couple of global variables to exist, JS and Set. CommonJS platforms encourage us to avoid global variables and so we need to import the modules we need into each spec file. Add the following to the top of example/spec/set_spec.js to load jstest and the Set class.

// example/spec/set_spec.js

var JS  = require('jstest'),
    Set = require('../lib/set').Set

If you want to run the tests both on the server and in the browser, you’ll either need to use a tool like browserify to resolve the require() statements, or add a little more boilerplate around the test so it can find the variables it needs whether they are globals or CommonJS modules.

(If you use browserify, you’ll need to pass --noparse jstest on the command line. jstest is a self-contained file that’s already gone through a browserify-like build process, and you’ll get lots of errors unless you tell browserify not to process it.)

// example/spec/set_spec.js

(function() {

var JS  = this.JS  || require('jstest'),
    Set = this.Set || require('../lib/set').Set

JS.Test.describe('Set', function() { with(this) {
  // ...
}})

})()

jstest exports a CommonJS module out of the box, but our Set class doesn’t, so let’s add a couple of lines at the end of example/lib/set.js to turn it into a proper module:

// example/lib/set.js

if (typeof exports === 'object')
  exports.Set = Set

Having done this, we can create a script to run our tests. All it does is load jstest, load all the specs, and execute them:

// example/console.js

var JS = require('jstest')
require('./spec/set_spec')
JS.Test.autorun()

This script is enough to run the tests on various CommonJS-based platforms.