Skip to content

Instantly share code, notes, and snippets.

@hopsoft
Last active August 29, 2015 14:08
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 hopsoft/22957f40744fb198ee87 to your computer and use it in GitHub Desktop.
Save hopsoft/22957f40744fb198ee87 to your computer and use it in GitHub Desktop.
A simple JavaScript test framework
(function () {
var suite, test, assert, defaultPrinter;
defaultPrinter = function () {
console.log(this.passed, this.name);
};
suite = function (description, callback, printer) {
var context = { name: [description] };
context.printer = printer || defaultPrinter;
callback.call(context);
};
assert = function (self, description, value) {
self.printer.call({
name: self.name.concat([description]),
passed: !!value
});
};
test = function (self, description, callback) {
var context = { printer: self.printer };
context.name = self.name.concat([description]);
callback.call(context);
};
})();
// Usage Example
suite("contrived example", function () {
test(this, "auto", function () {
test(this, "car", function () {
assert(this, "has engine", true);
assert(this, "has 4 wheels", true);
assert(this, "can accelerate", true);
assert(this, "can stop", true);
test(this, "yugo", function () {
// async example
var yugo = this;
setTimeout(function () {
assert(yugo, "is slow", true);
}, 1000);
assert(this, "is crappy", true);
});
test(this, "mustang", function () {
assert(this, "is fast", true);
assert(this, "is fun", true);
});
});
test(this, "truck", function () {
test(this, "f150", function () {
assert(this, "can haul", true);
assert(this, "can tow", true);
});
});
});
});
// want different semantics?
var group = suite;
var describe = test;
var verify = assert;
// want to change the printed output?
var minimalPrinter = function () {
if (!this.passed) {
console.log("FAIL: " + this.name.join(" "));
}
};
@robmerrell
Copy link

You don't need the .call() in javascript.

You can just do:

var a = function() { alert('blah'); }
a();

@braindev
Copy link

what about testing async stuff?

@hopsoft
Copy link
Author

hopsoft commented Oct 22, 2014

I did away with call on the outer closure, but need it in the other places as I'm using it to control the this context.

@hopsoft
Copy link
Author

hopsoft commented Oct 22, 2014

@braindev
Copy link

Can you test things like asyncAdd?

function asyncAdd(x, y, resultFn) {
  setTimeout(function(){
    resultFn(x+y);
  }, 0);
}

asyncAdd(1, 2, function(result){
  console.log("1 + 2 is", result);
});

@braindev
Copy link

also assert is a built in function in nodejs

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