Archive

javascript test driven development with qunit

I have been getting deep into TDD lately, and qUnit became the framework of my choice. This is how I decided: I went to John Resing's site and looked what he uses :) (actually wrote/co-wrote it).

Anyway, I love TDD now. It is a lot of work, and write a good test is harder that writing a good code, but it will make you much better developer who writes much better code.

I have written a simple loader which allows you to load qUnit from an external file, rather than having to have to include the HTML on the page, which is nice in combination with some client side or server side mechanism that will include your tests with dev - exclude in production.

(function ($) {

    //test case init

    var stringBuilder = function () {

        var s = [];
        return {
            // appends
            append: function (v) {
                if (v) {
                    s.push(v);
                }
            },
            // clears
            clear: function () {
                s.length = 1;
            },
            // converts to string
            toString: function () {
                return s.join("");
            }
        }
    };

    var sb = stringBuilder();
    sb.append("<div style=\"position:absolute; right:0%; width:350px;\">");
    sb.append("<h1 id=\"qunit-header\">QUnit Test Suite</h1>");
    sb.append("<h2 id=\"qunit-banner\"></h2>");
    sb.append("<div id=\"qunit-testrunner-toolbar\"></div>");
    sb.append("<h2 id=\"qunit-userAgent\"></h2>");
    sb.append("<ol id=\"qunit-tests\"></ol>");
    sb.append("<div id=\"qunit-fixture\">test markup</div>");
    sb.append("</div>");
    $("body").append(sb.toString());

})(jQuery);

Here is how I like to write my tests: despite of all of the methods being available as globals, this might be dangerous in a complex app, so I wrap the code in a closure, and use the namespaced methods which are available under the qunit namespace:

/*test 1*/
(function (T, $) {

    //get elements
    var doc = $(document);

    T.module("First Test");

    T.test("Toggle", function () {

        //how many tests are expected to pass:
        expect(2);

        T.equals("block", "block");

        T.equals("none", "none");

    });

})(QUnit, jQuery);

To get some ideas how to write tests, there are some great test cases written as examples on the bottom of the qunit page showing how jquery itself is being tested.

I have seen this quote somewhere recently: "Debugging sucks, TDD rocks!"

Comments: