Skip to content

Instantly share code, notes, and snippets.

@donavon
Forked from joakimbeng/test_runner.js
Last active January 22, 2020 23:08
Show Gist options
  • Save donavon/26acb8b066f001be4914af8816f6054d to your computer and use it in GitHub Desktop.
Save donavon/26acb8b066f001be4914af8816f6054d to your computer and use it in GitHub Desktop.
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);
if (!testToRun.test.length) 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!'));
}
};
this.autoRun = true;
setTimeout(function () {
if (autoRun) run();
}, 1);
})();
// Example usage:
// Sync test
test('1+1 equals 2', function () {
assert(1+1 === 2, '1+1 should be 2');
});
// Async test
test('1+2 equals 3', function (done) {
setTimeout(function () {
assert(1+2 === 3, '1+2 should be 3');
done();
}, 200);
});
// Add a failing test:
test('1+2 equals 4', function () {
assert(1+2 === 4, '1+2 should also be 4');
});
// All tests will run automatically. If you need to perform any async functions before the tests run,
// set `autoRun = false` and call `run` manually.
// World's smallest assertion library by @snuggsi (https://twitter.com/snuggsi/status/565531862895169536):
function assert (condition, message) {
if (!condition) throw new Error(message);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment