When I got really serious with my JavaScript and understood it well enough I always wanted to have some kind of unit testing framework. Unfortunately though there really does not seem to be anything available that really works and also has some kind of documentation on how to use it. I’ve been following JsUnit for a few year now but nobody seems to be using it. I tried using it myself over the years for mulitple times but like everyone else, I too seem to be lacking the necessary brain capacity to figure it out. So this weekend I incubated one myself and you know what? It’s not even that hard at all…
For my immediate testing needs it turned out I only needed two methods: areEqual
and areEqualArrays
. So I wrapped these into a Assert object:
[JavaScript]var Assert = {
areEqual: function(expected, actual, msg) {
if(expected != actual)
Kinky.fail(expected, actual, msg);
},
areEqualArrays: function(expected, actual, msg) {
if(expected.length != actual.length) {
Kinky.fail(expected, actual, msg);
return;
}
expected.each(function(item, index) {
Assert.areEqual(item, actual[index]);
});
}
}[/JavaScript]
As you can see the Assert
object depends on the Kinky
object so
let’s have that as well:
[JavaScript]var Kinky = {
failed: false,
output: new Alerter(),
fail: function(expected, actual, msg) {
if(this.failed) return;
this.failed = true;
this.output.writeLine(“Expected: ” + expected + “, was: ” + actual + “: ” + msg);
},
run: function(testFixture, output) {
if(output)
this.output = new Writer($(output));;
for(test in testFixture) {
testFixture[test]();
if(this.failed) return;
this.output.writeLine(test + ” done.”);
}
}
}[/JavaScript]
The last thing we need is the Alerter
that’s referenced by the Kinky
class:
[JavaScript]var Alerter = Class.create();
Alerter.prototype = {
initialize: function(beSilent) { this.beSilent = beSilent; },
writeLine: function(str) { if((!this.beSilent) || Kinky.failed) alert(str); }
}[/JavaScript]
The Alerter
is somewhat a last-ditch effort to raise test messages. We usually want to have some more friendly output so we have this Writer
class that’s able to redirect messages to document elements:
[JavaScript]var Writer = Class.create();
Writer.prototype = {
initialize: function(elm) { this.elm = elm; },
writeLine: function(str) { new Insertion.Bottom(this.elm, str + “
“); }
}[/JavaScript]
To have Kinky use it we need to assign it to Kinky.output
like so:
[JavaScript]Kinky.output = new Writer($(‘theOutputElement’));[/JavaScript]
Or use the extended run
function:
[JavaScript]Kinky.run(someTestFixture, ‘theOutputElement’);[/JavaScript]
The $
function is a Prototype function that returns the DOM node confirming to the id supplied.