test.js
fs = require("fs"); vm = require("vm"); exports.run = function(options){ console.log("-- Testing " + (options.file || "on empty context") + " --"); var script = options.file && load_script(options.file); for(test_name in options.tests){ process.stdout.write(test_name + ": "); run_test(script, options.tests[test_name], options.setup, options.teardown); console.log("OK"); } }; function load_script(path){ var content = fs.readFileSync(path, "utf8"); return vm.createScript(content, path); } function run_test(script, test, setup, teardown){ var context = {}; if(setup){ setup(context); } if(script){ script.runInNewContext(context); } test(context); if(teardown){ teardown(context); } }
Available options:
file: a path to a js file that should be used as tests context.
tests: an array or object of test functions to execute.
setup: a function to execute before running each test.
teardown: a function to execute after running each test.
Exemple usage testing function ‘hello’ in source file foo.js :
foo.js
function hello(name){ return "Hello " + name; }
test_foo.js
#!/usr/bin/env node assert = require("assert"); test = require("./test"); test.run({ file: "foo.js", tests: { "hello greets correctly": function(context){ assert.equal("Hello world", context.hello("world")); } } });