Skip to content

Instantly share code, notes, and snippets.

@wjramos
Last active March 15, 2018 18:58
Show Gist options
  • Save wjramos/d4571739c0d6a14172d2654e92746530 to your computer and use it in GitHub Desktop.
Save wjramos/d4571739c0d6a14172d2654e92746530 to your computer and use it in GitHub Desktop.
Dependency-less unit-testing
const assert = require('assert');
const GREEN = '\x1b[32m';
const RED = '\x1b[31m';
const WHITE = '\x1b[37m';
const printFailure = failure => console.error(`${RED}
❌ FAILURE: ${failure}`);
const printSuccess = success => console.log(`${GREEN}
✅ SUCCESS: ${success}`);
const printSection = section => console.log(`${WHITE}
-------------------
${section}
-------------------`);
const printFailed = (failures, count) => console.error(`${RED}
${failures.length} tests failed (out of ${count} tests total)`);
const printPassed = count => console.log(`${GREEN}
🎉 All tests passed! (${count} tests total) 🎉`);
const test = ((failures, count) => (func, io = []) => {
if (func) {
return (() => {
successes = [];
testFailures = []
io.forEach(([input, expected, message = '', spread], i) => {
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);
}
});
printSection(func.name);
if (successes) {
successes.forEach(printSuccess);
}
if (testFailures.length) {
testFailures.forEach(printFailure);
}
failures = failures.concat(testFailures);
})();
}
if (failures.length) {
printSection('TEST FAILURES');
failures.forEach(printFailure);
printFailed(failures, count);
process.exit(1);
}
return printPassed(count);
})([], 0);
// Function under test
const dummyFunc = (str = '') => str.split('.');
// Execute suite of tests
test(dummyFunc, [
['www.google.com', ['www', 'google', 'com'], 'Should split a string to array on period'],
['hello', ['hello'], 'Should return array with entire string of no period present'],
]);
// Function under test
const multipleArgFunc = (arr = [], omit = []) => arr.filter(val => !omit.includes(val));
// Execute suite of tests
test(multipleArgFunc, [
[
[[1, 2, 3], [2]],
[1, 3],
'Should return an array with values from second array filtered out if any matches exist',
true,
],
]);
// Roll up and output full report
test();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment