testit/dist/testit.js

90 lines
2.8 KiB
JavaScript
Raw Normal View History

2020-09-08 22:37:54 +00:00
/*! Test.it v 0.9.0 | MIT | https://github.com/n2geoff/testit */
const test = {
"log": console.log,
"_tests": {},
"run": function run(errors, next) {
if(typeof errors !== "boolean") {
next = errors;
errors = true;
}
2020-09-08 22:37:54 +00:00
let tests = this._tests || [];
let failed = [];
let passed = [];
2020-09-08 22:37:54 +00:00
Object.keys(tests).forEach((name) => {
let test = tests[name];
2020-09-08 22:37:54 +00:00
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:37:54 +00:00
});
2020-09-08 22:37:54 +00:00
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:37:54 +00:00
return failed.length ? false : true;
}
},
"it": function it(tests) {
this._tests = tests;
return this;
},
"expects": function expects(val) {
return {
"to": {
"be": {
"a": (type) => { return test.expects(val).to.be.an(type); },
"an": (type) => {
2020-09-08 22:37:54 +00:00
if(["array"].indexOf(type) !== -1) {
if(val.constructor.name.toLowerCase() !== "array") {
throw new Error(`expected ${typeof val} to be an ${type}`);
}
2020-09-08 22:37:54 +00:00
return true;
}
2020-09-08 22:37:54 +00:00
if(typeof val !== type) {
throw new Error(`expected ${typeof val} to be an ${type}`);
}
},
2020-09-08 22:37:54 +00:00
"ok": () => { return test.expects(val).to.exist(); },
"like": (comp) => {
if(val != comp) {
throw new Error(`expected ${val} == ${comp}`);
}
2020-09-08 22:37:54 +00:00
}
},
"equal": (comp) => {
if(val !== comp) {
throw new Error(`expected ${val} === ${comp}`);
}
},
"exist": () => {
if(!val) {
throw new Error(`expected ${val} to be truthy`);
}
},
"pass": () => { return true; },
"fail": (msg) => { throw new Error(msg); }
}
};
}
};
2020-09-08 22:37:54 +00:00
export default test;