Ruby Guard style testing with Node.js
Great way for automating the running of tests / specs when building a JavaScript project. I'm using mocha for the the tests but have a nice little Makefile for building the project and running tests / coverage.
I tend to keep all my dev/library files under either a lib/ or a src/ folder and my test files under either a test/ or spec/ folder.
First create a small Node.js based script using nodewatch for watching either your unit tests or source directory such as utils/watcher.js.
var watch = require('nodewatch');
var util = require('util');
var exec = require('child_process').exec;
watch
.add("./test", true)
.add("./src", true)
.onChange(function(file, prev, curr, action) {
exec("make test", function(error, stdout, stderr) {
util.print('stdout: ' + stdout);
util.print('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
});
Now create a Makefile to simplify a few command. While this is not necessary it's a good habit to get into and means you can always run the 'make test' command at any point to test.
test:
mocha --recursive --reporter spec --ui bdd --colors --grunt
watch:
node utils/watcher.js
.PHONY test watch
The benefits here are Mocha also gives me growl notifications so I don't even need to leave my editor and I can see these fire off each time I save a file in either my dev or test folders.
Written by David Rhys White
Related protips
3 Responses
Please provide directory structure and examples.
Hi scarver2,
I've added a bit more detail to this so you can see whats going on. Let me know if you still need more detail and I'll setup a Github repo with quick example.
David
In a Node environment, why would you use make instead of grunt?