Mon, 29. April 2013
Testing hybrid project is just too difficult. It should be simple to write sources and tests without any boilerplate for Node.js and browsers, and run it headlessly on a build server.
Please also read the follow up post: How to run Node.js tests in your browser with Mocha.
Phantom.JS is a headless WebKit browser. If you have not heard about it, go check it out.
It requires a JavaScript file that drives the browser using the provided API. That is great for all sorts of automation, but for just running some unit tests, I wanted something very simple.
console.error
This can now be done with Phantomic. Phantomic behaves in a unix friendly way which allows you to write
$ phantomic < test-script.js
This works great with Browserify as well:
$ browserify test-script.js | phantomic
You can find Phantomic on GitHub.
Browerify is a fantastic tool that transmogrifies your Node sources to work in the browser. But I also wanted to have standalone test web pages, that contain the sources including all test cases and just show the console output. Producing a JavaScript file with all the sources and tests is easy enough:
$ browserify `ls test/*` > all.js
Great! But I wanted something that wraps the JavaScript in a nicely styled HTML page and shows the console messages. Therefore I created Consolify, which uses the Browserify API to create the script bundle and combines it with an HTML template:
$ consolify `ls test/*` > all.html
This is what it looks like if you open the generated page in a browser:
You can find Consolify on GitHub as well.
In some cases, your unit testing framework might do things that are either not
supported by Browserify or cause problems in Phantom.JS for random reasons. For
example, Phantom.JS does not support bind yet. If your code
depends on it, just create a fixture JavaScript file, for example in
test/fixture/shim.js
:
if (!Function.prototype.bind) {
Function.prototype.bind = function (scope) {
var fn = this;
return function () {
return fn.apply(scope, arguments);
};
};
}
And then include the file before the test cases:
$ consolify test/fixture/shim.js `ls test/test-*` > all.html
For Node testing, I prefer to use utest - The minimal unit testing library. With release v0.0.8, utest now supports Browserify (and maybe others). It ships with the above shim and a new reporter that logs to the console. Happy browser testing!
I changed the build for two of my projects. You can run the test cases in your browser:
I'm very much interested in your feedback. Please drop me a line!
Please also read the follow up post: How to run Node.js tests in your browser with Mocha.