Skip to content

Instantly share code, notes, and snippets.

@kabootit
Forked from freedmand/tester.js
Last active November 5, 2018 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kabootit/767370b3de0e0784d2d7a11424e7b48a to your computer and use it in GitHub Desktop.
Save kabootit/767370b3de0e0784d2d7a11424e7b48a to your computer and use it in GitHub Desktop.
JavaScript unit testing in under 30 lines
const PASS = ['32']; // green
const FAIL = ['31', '1']; // red, bold
function logStyle(ansiEscapeCodes, text) {
console.log(`\x1b[${ansiEscapeCodes.join(';')}m${text}\x1b[0m`);
}
class Tester {
constructor() {}
test(name, fn) {
try {
fn.bind(this)();
logStyle(PASS, `${name} PASSED`);
}
catch (e) {
logStyle(FAIL, `${name} FAILED:
${e}`);
process.on('exit', () => (process.exitCode = 1));
}
}
assertEquals(arg1, arg2) {
if (arg1 != arg2) throw new Error(`Expected ${arg1} to equal ${arg2}`);
}
assert(condition) {
if (!condition) throw new Error(`Expected ${condition} to be truthy`);
}
}
/*
Usage:
const t = new Tester();
t.test('testName', () => {
t.assertEquals('dog'.length, 3); // will pass
});
t.test('anotherTestName', () => {
t.assert(false); // will fail
});
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment