Skip to content

Instantly share code, notes, and snippets.

@Xvezda
Last active October 11, 2020 18:15
Show Gist options
  • Save Xvezda/b7f56d9d6975b5b3695c0ba27c37f1a9 to your computer and use it in GitHub Desktop.
Save Xvezda/b7f56d9d6975b5b3695c0ba27c37f1a9 to your computer and use it in GitHub Desktop.
Minimal JavaScript test setup
#!/usr/bin/env node
/*!
* Copyright (c) 2020 Xvezda <xvezda@naver.com>
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
function ordinal(i) {
if (Number.isNaN()) throw TypeError('argument is not a number');
if (i <= 0) throw Error('argument is smaller than 1');
return i + (['st', 'nd', 'rd'][i-1] || 'th');
}
function tests() {
var i;
for (i = 0; i < arguments.length; ++i) {
if (i) console.log();
var test = arguments[i];
if (typeof test !== 'function') {
console.error(ordinal(i+1) + ' testcase is not a function');
continue;
}
var testString = test.toString();
var testName;
if (testString.startsWith('function') && (testName=testString.slice(8, testString.indexOf('(')).trim())) {
console.log(testName + ' is running');
} else {
console.log(ordinal(i+1) + ' testcase is running');
}
try {
test();
} catch (e) {
console.error(e.name + ': ' + e.message);
continue;
}
}
}
tests(
undefined,
function() {
console.assert(1 === 1);
},
function named() {
console.assert(1 === 1);
},
function() {
console.assert(1 === 0, '1 is not equal to 0');
},
function namedError() {
console.assert(1 === 0, '1 is not equal to 0');
},
function() {
throw Error('BOOM!');
}
);
#!/bin/sh
# node test.js 2>&1 >/dev/null | grep '.' && echo failed || echo passed
node test.js 2>&1 >/dev/null | grep '.' && exit 1 || exit 0
@Xvezda
Copy link
Author

Xvezda commented Oct 11, 2020

output

1st testcase is not a function
2nd testcase is running
named is running
4th testcase is running
Assertion failed: 1 is not equal to 0
namedError is running
Assertion failed: 1 is not equal to 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment