Skip to content

Instantly share code, notes, and snippets.

@nhunzaker
Created March 23, 2012 20:03
Show Gist options
  • Save nhunzaker/2174418 to your computer and use it in GitHub Desktop.
Save nhunzaker/2174418 to your computer and use it in GitHub Desktop.
A super simple self-tested testing framework for javascript
// Implementation
// -------------------------------------------------- //
function assert(condition, opt_message) {
'use strict';
if (!condition) {
var msg = 'Assertion failed';
if (opt_message) {
msg = msg + ': ' + opt_message;
}
throw new Error(msg);
}
}
function describe(obj) {
"use strict";
var test = {};
test.target = obj;
test.__preaction = test.__postaction = function() {
return test;
};
test.before = function(action) {
test.__preaction = action;
return test;
};
test.after = function(action) {
test.__postaction = action;
return test;
};
test.do = function(assertions) {
console.log(new Array(80).join("-"));
var passed = 0,
failed = 0;
for (var assert in assertions) {
try {
assertions[assert].call(obj, test.__preaction());
passed++;
console.log("\u2714", assert);
} catch(x) {
console.log("\u2716", assert, ":", x.message);
failed++;
}
}
console.log(new Array(80).join("-"));
console.log("%s passed. %s failed", passed, failed);
return test;
};
return test;
}
// Testing
// -------------------------------------------------- //
describe(String)
.before(function() {
return "I'm a sample pre-action return value";
})
.after(function() {
return "I'm a sample post-action return value";
})
.do({
"it should be sane": function() {
assert(true, "this testing library is clearly insane");
},
"it should be able to use before actions": function(before) {
assert(before === "I'm a sample pre-action return value", "Before statement failed");
},
"it should understand scope": function() {
assert(this === String, "Scope management failed");
},
"it should handle failing tests": function() {
var exception;
try {
assert(this === Boolean);
} catch(x) {
exception = x;
}
assert(exception instanceof Error);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment