A small and simple Javascript test runner
/**
* A Javascript test runner in 20 lines of code
* From http://joakimbeng.eu01.aws.af.cm/a-javascript-test-runner-in-20-lines/
*/
(function () {
// The test queue:
var tests = [];
// Function to add tests:
this.test = function test (name, cb) {
tests.push({name: name, test: cb});
};
this.run = function run () {
var i = 0, testToRun;
(function next (err) {
// Log status for last test run:
if (testToRun) console[err ? 'error' : 'log'](err ? '✘' : '✔', testToRun.name);
// Abort if last test failed or out of tests:
if (err || !(testToRun = tests[i++])) return done(err);
// Run test:
try {
testToRun.test.call(testToRun.test, next);
} catch (err) {
next(err);
}
})();
function done (err) {
// Show remaining tests as skipped:
tests.slice(i).map(function (skippedTest) { console.log('-', skippedTest.name); });
// We're finished:
console[err ? 'error' : 'log']('\nTests ' + (err ? 'failed!\n' + err.stack : 'succeeded!'));
}
};
})();
// Example usage:
test('1+1 equals 2', function (done) {
assert(1+1 === 2, '1+1 should be 2');
done();
});
test('1+2 equals 3', function (done) {
assert(1+2 === 3, '1+2 should be 3');
done();
});
// Add a failing test:
test('1+2 equals 4', function (done) {
assert(1+2 === 4, '1+2 should also be 4');
done();
});
// Run all tests:
run();
// World's smallest assertion library by @snuggsi (https://twitter.com/snuggsi/status/565531862895169536):
function assert (condition, message) {
if (!condition) throw new Error(message);
}