1

My Javascript Unit Testing Engine

by Alexandru Lungu 28. martie 2011 03:01

 

I’ve created this more than 5 years ago and from then I did very few modifications/addings to it.

The idea is simple – we have a test object that has methods that start with “test” word. I never pollute the global namespace with anything – including functions – so at the start individual/anonymous functions could not be added. Recently, I also added this feature.

It still remains with only one assert, $Test.ok – if its first parameter is false the test fails. I had in plan to implement others, but it was enough because it can simmulate all the others.

The example should explain how it should be used:

var MyTestObject = {
    testMethod1: function ()
    {
        $Test.ok(true, "True assert");
    },
    testMethod2: function ()
    {
        //Multiple asserts - al must be true in order for the test to pass.
        $Test.ok(true, "True assert");
        $Test.ok(false, "False assert");
    },
    name: "MyName",
    testName: function ()
    {
        this.changeName();
        $Test.ok(this.name == "MyName", this.name + "!=MyName");
    },
    changeName: function ()
    {
        this.name = "ChangedName";
    }
};

//adding a test object; all its methods that start with "test" will be executed
$Test.Add("My Test Object", MyTestObject);

//adding a test function and with the name "Func" for the test
$Test.Add("Func", function ()
{
    $Test.ok(5 == 4, "5==4");
});

//adding a test function with no name for the test
$Test.Add(function ()
{
    $Test.ok(5 == 5, "5==5");
});


//Runs all added functions and all functions that start with "test" from the added test objects
$Test.Run();
And this will produce the following output:

First are shown the anonymous functions (Test Object: Functions) and then the test methods from the test objects.

I know that it may appear rudimentary comparative to the actual unit testing frameworks like jsUnit, Screw.unit, js-test-driver, etc, but it did, and still does the job.

 

Download UnitTesting.js (5.52 kb)
Download Example.htm (1.70 kb)

Tags: ,

Programming

Comments (1) -

George
George Romania
30.03.2011 23:40:25 #

Nice

Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading






Powered by BlogEngine.NET 2.0.0.36
Original Design by Laptop Geek, Adapted by onesoft