Skip to content

Instantly share code, notes, and snippets.

@wjramos
Last active March 15, 2018 20:53
Show Gist options
  • Save wjramos/b76ea73f3cf272d3d61988971491deeb to your computer and use it in GitHub Desktop.
Save wjramos/b76ea73f3cf272d3d61988971491deeb to your computer and use it in GitHub Desktop.
const assert = require('assert');
const GREEN = '\x1b[32m';
const RED = '\x1b[31m';
const WHITE = '\x1b[37m';
class Test {
constructor() {
this.failures = [];
this.count = 0;
}
printFailure(failure) {
console.error(`${RED}
❌ FAILURE: ${failure}`);
}
printSuccess(success) {
console.log(`${GREEN}
✅ SUCCESS: ${success}`);
}
printSection(section) {
console.log(`${WHITE}
${'-'.repeat(section.length + 4)}
${section}
${'-'.repeat(section.length + 4)}`);
}
printFailed() {
console.error(`${RED}
${this.failures.length} tests failed (out of ${this.count} tests total)`);
}
printPassed() {
console.log(`${GREEN}
🎉 All tests passed! (${this.count} tests total) 🎉`);
}
run(func, io = []) {
const successes = [];
const testFailures = []
io.forEach(([input, expected, message = '', spread], i) => {
this.count++;
let result;
if (spread) {
result = func(...input);
} else {
result = func(input);
}
try {
assert.deepEqual(
result,
expected,
`[${func.name}] (${i + 1}) Expected "${result}" to equal "${expected}": ${message}`
);
successes.push(`${func.name} (${message})`);
} catch (e) {
testFailures.push(e);
}
});
this.printSection(func.name);
if (successes) {
successes.forEach(this.printSuccess);
}
if (testFailures.length) {
testFailures.forEach(this.printFailure);
}
this.failures = this.failures.concat(testFailures);
}
result() {
if (this.failures.length) {
this.printSection('TEST FAILURES');
this.failures.forEach(this.printFailure);
printFailed();
process.exit(1);
}
return this.printPassed();
}
}
module.exports = Test;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment