refactored to support browser and nodejs. also seperated out execution to a run() to allow loading tests from files

This commit is contained in:
Geoff Doty 2018-04-02 04:27:08 -04:00
parent 5faca9e998
commit ba94c435ad
1 changed files with 62 additions and 43 deletions

View File

@ -1,46 +1,65 @@
'use strict'; /* Test.it v 0.5 | MIT | https://github.com/n2geoff/testit */
(function(root, factory) {
// support browser & commonjs
if(typeof module === "object" && module.exports) {
module.exports = factory(root.test);
} else {
root.test = factory(root.test);
}
}(this, function() {
'use strict';
const test = { const test = {
it: function(tests, next) { _tests: {},
// capture results run: function(next) {
let failed = [];
let passed = [];
// loop through tests let tests = this._tests;
Object.keys(tests).forEach(function(name) { // capture results
let test = tests[name]; let failed = [];
let passed = [];
// execute // loop through tests
try { Object.keys(tests).forEach(function(name) {
test(); let test = tests[name];
passed.push(`\n+ ${name}`);
} catch (err) {
// TODO: include error stack option
// let back = err.stack.split('\n')[2];
// let re = /(?<=\()(.*?)(?=\))/g;
// let trace = re.exec(back)[0];
failed.push(`\n- ${name}`);
console.error(err);
// failed.push(`\n- ${name} - - ${trace}`);
}
});
// summary // execute
if(typeof next === 'function') { try {
return next({ test();
pass: passed, passed.push(`\n+ ${name}`);
fail: failed } catch (err) {
// TODO: include error stack option
// let back = err.stack.split('\n')[2];
// let re = /(?<=\()(.*?)(?=\))/g;
// let trace = re.exec(back)[0];
failed.push(`\n- ${name}`);
console.error(err);
// failed.push(`\n- ${name} - - ${trace}`);
}
}); });
} else {
console.log(...passed, ...failed);
console.log(`\n# tests ${failed.length + passed.length} pass ${passed.length} fail ${failed.length}`);
return failed.length ? false : true; // summary
} if(typeof next === 'function') {
}, return next({
assert: function (e, a) { if (e != a) throw Error(`expected ${e} == ${a}`); }, pass: passed,
equals: function (e, a) { if (e !== a) throw Error(`expected ${e} === ${a}`); }, fail: failed
exists: function (v) { if (!v) throw Error(`exists value ${v}`); }, });
pass: function () { return true; }, } else {
fail: function (m) { throw Error(m); } console.log(...passed, ...failed);
} console.log(`\n# tests ${failed.length + passed.length} pass ${passed.length} fail ${failed.length}`);
return failed.length ? false : true;
}
},
it: function(tests) {
this._tests = tests;
return this;
},
assert: function (e, a) { if (e != a) throw Error(`expected ${e} == ${a}`); },
equals: function (e, a) { if (e !== a) throw Error(`expected ${e} === ${a}`); },
exists: function (v) { if (!v) throw Error(`exists value ${v}`); },
pass: function () { return true; },
fail: function (m) { throw Error(m); }
}
return test;
}));