testit/src/testit.js

106 lines
3.5 KiB
JavaScript
Raw Normal View History

2018-12-02 08:43:35 +00:00
/*! Test.it v 0.8.0 | MIT | https://github.com/n2geoff/testit */
2019-01-13 21:47:12 +00:00
;(function (root, factory) {
2018-04-02 09:21:16 +00:00
"use strict";
// support browser & commonjs
2018-04-02 09:21:16 +00:00
if (typeof module === "object" && module.exports) {
module.exports = factory(root.test);
} else {
root.test = factory(root.test);
}
2018-04-02 09:21:16 +00:00
}(this, function () {
"use strict";
2018-03-31 22:45:35 +00:00
const test = {
2018-04-02 09:21:16 +00:00
"_tests": {},
2018-12-02 09:30:08 +00:00
"run": function run(errors, next) {
2019-01-13 22:09:21 +00:00
// TODO: rewrite to allow a show errors flag (optional)
2018-12-02 09:30:08 +00:00
if(typeof errors !== "boolean") {
next = errors;
errors = true;
}
2018-04-02 09:21:16 +00:00
let tests = this._tests;
// capture results
let failed = [];
let passed = [];
// loop through tests
2018-11-09 16:18:46 +00:00
Object.keys(tests).forEach((name) => {
let test = tests[name];
// execute
try {
test();
2018-12-02 08:43:35 +00:00
passed.push(`\n+OK ${name}`);
} catch (err) {
2018-12-02 09:30:08 +00:00
if (errors) {
failed.push(`\n-ERR ${name} \n --- \n ${err.stack} \n ---`);
} else {
failed.push(`\n-ERR ${name}`);
}
}
2018-03-31 22:45:35 +00:00
});
// summary
2018-04-02 09:21:16 +00:00
if(typeof next === "function") {
return next({
pass: passed,
fail: failed
});
} else {
console.log(...passed, ...failed);
console.log(`\n# tests ${failed.length + passed.length} pass ${passed.length} fail ${failed.length}`);
return failed.length ? false : true;
}
},
2018-11-09 16:18:46 +00:00
"it": function it(tests) {
this._tests = tests;
return this;
},
2018-11-09 16:18:46 +00:00
"expects": function expects(val) {
return {
"to": {
"be": {
2019-01-13 22:09:21 +00:00
"a": (type) => { return test.expects(val).to.be.an(type); },
"an": (type) => {
if(['array'].indexOf(type) !== -1) {
if(val.constructor.name.toLowerCase() !== 'array') {
throw new Error(`expected ${typeof val} to be an ${type}`);
}
return true;
}
if(typeof val !== type) {
throw new Error(`expected ${typeof val} to be an ${type}`);
}
},
2019-01-13 22:09:21 +00:00
"ok": () => { return test.expects(val).to.exist(); },
"like": (comp) => {
if(val != comp) {
throw new Error(`expected ${val} == ${comp}`);
}
}
},
"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; },
2019-01-13 22:09:21 +00:00
"fail": (msg) => { throw new Error(msg); }
}
};
}
2018-04-02 09:21:16 +00:00
};
2018-03-31 22:45:35 +00:00
return test;
}));