Skip to content

Instantly share code, notes, and snippets.

@tmlbl
Last active January 23, 2020 19:52
Show Gist options
  • Save tmlbl/f28231bf49be11c8f4c1 to your computer and use it in GitHub Desktop.
Save tmlbl/f28231bf49be11c8f4c1 to your computer and use it in GitHub Desktop.
Asynchronous test runner
module.exports = Runner;
function Runner() {
this.stack = [];
this.passed = 0;
this.failed = 0;
}
Runner.prototype.it = function (msg, test) {
this.stack.push(new Test(msg, test));
};
Runner.prototype.run = function () {
this.test = this.stack.shift();
if (!this.test) {
var exitCode = this.failed.length ? 1 : 0;
this.summary();
process.exit(exitCode);
};
console.log(this.test.msg);
var self = this;
this.test.func(function () {
self.report();
self.run.bind(self)();
});
};
Runner.prototype.summary = function () {
console.log('Passed: ' + this.passed +
' Failed: ' + this.failed);
};
Runner.prototype.report = function () {
if (this.test.passed) {
console.log('\tPASSED');
this.passed++;
} else {
console.log('\tFAILED');
this.failed++;
}
};
Runner.prototype.fail = function () {
this.test.fail();
};
function Test(msg, func) {
this.msg = msg;
this.func = func;
this.passed = true;
}
Test.prototype.fail = function () {
this.passed = false;
};
var TestRunner = require('./runner.js'),
test = new TestRunner();
test.it('Should do something that takes a second', function (next) {
setTimeout(next, 1000);
});
test.it('Should do something else', function (next) {
next();
});
test.it('Should try to do something and fail', function (next) {
test.fail();
next();
});
test.run();
@tmlbl
Copy link
Author

tmlbl commented Nov 3, 2014

Should do something that takes a second
    PASSED
Should do something else
    PASSED
Should try to do something and fail
    FAILED
Passed: 2 Failed: 1

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