Skip to content

Instantly share code, notes, and snippets.

@joakimbeng
Last active July 12, 2020 22:38
Show Gist options
  • Save joakimbeng/8f57dae814a4802e2ae6 to your computer and use it in GitHub Desktop.
Save joakimbeng/8f57dae814a4802e2ae6 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);
} 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);
}
@donavon
Copy link

donavon commented Mar 16, 2017

I also made it so that you don't need to specially call run. Enjoy!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment