testit/src/testit.js

64 lines
1.7 KiB
JavaScript
Raw Normal View History

2023-03-15 13:54:36 +00:00
/*! Test.it v1.1.2 | MIT | https://github.com/n2geoff/testit */
2020-09-08 22:29:56 +00:00
const test = {
2020-09-08 22:37:24 +00:00
"log": console.log, // eslint-disable-line
2023-03-15 13:54:36 +00:00
"version": "v1.1.2",
2020-09-08 22:29:56 +00:00
"_tests": {},
"run": function run(errors, next) {
// TODO: rewrite to allow a show errors flag (optional)
if(typeof errors !== "boolean") {
next = errors;
errors = true;
}
2018-04-02 09:21:16 +00:00
2020-09-08 22:29:56 +00:00
let tests = this._tests || [];
// capture results
let failed = [];
let passed = [];
2020-09-08 22:29:56 +00:00
// loop through tests
Object.keys(tests).forEach((name) => {
let test = tests[name];
2020-09-08 22:29:56 +00:00
// execute
try {
test();
passed.push(`\n+OK ${name}`);
} catch (err) {
if (errors) {
failed.push(`\n-ERR ${name} \n --- \n ${err.stack} \n ---`);
} else {
failed.push(`\n-ERR ${name}`);
}
}
2020-09-08 22:29:56 +00:00
});
2020-09-08 22:29:56 +00:00
// summary
if(typeof next === "function") {
return next({
pass: passed,
fail: failed
});
} else {
test.log(...passed, ...failed);
test.log(`\n# tests ${failed.length + passed.length} pass ${passed.length} fail ${failed.length}`);
2020-09-08 22:29:56 +00:00
return failed.length ? false : true;
}
},
"it": function it(tests) {
this._tests = tests;
return this;
},
2020-09-20 19:58:00 +00:00
"assert": (expression, msg) => {
try {
if(!expression) {
throw new Error(msg || "Assertion Failed");
2020-09-08 22:29:56 +00:00
}
2020-09-20 19:58:00 +00:00
} catch (e) {
throw new Error(msg);
}
2020-09-08 22:29:56 +00:00
}
};
2018-03-31 22:45:35 +00:00
2020-09-08 22:29:56 +00:00
export default test;