Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Last active February 2, 2021 20:57
Show Gist options
  • Select an option

  • Save dfkaye/0461d4805817c21a5609 to your computer and use it in GitHub Desktop.

Select an option

Save dfkaye/0461d4805817c21a5609 to your computer and use it in GitHub Desktop.
string#test ~ drive tests in javascript from strings as descriptors
// Idea: August 10, 14, 2014
// Implementation: February 2, 2021
// Embrace patching of prototypes, and de-clutter the global scope, to
// allow tests be driven by strings.
String.prototype.test = function(fn) {
var test = this
var assert = function(condition, msg) {
var status = condition ? "Pass" : "Fail"
var report = [status, ": ", test.valueOf(), " > ", condition]
var method = "log"
if (!condition) {
report.push(msg ? " ("+msg+")" : "")
method = "error"
}
console[method](report.join("").toString())
}
fn.call(test, assert)
}
// one assert per test
'should be two'.test(function(assert) {
var a = 1;
assert(2 * a === 2, "should equal 2");
'should run nested tests like a suite'.test(function(assert) {
var b = 2;
assert(typeof b == 'string', "b ain't no string")
// et cetera
});
});
/* Test output */
// Pass: should be two > true
// Fail: should run nested tests like a suite > false (b ain't no string)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment