Agile Zone is brought to you in partnership with:

I am a programmer and architect (the kind that writes code) with a focus on testing and open source; I maintain the PHPUnit_Selenium project. I believe programming is one of the hardest and most beautiful jobs in the world. Giorgio is a DZone MVB and is not an employee of DZone and has posted 635 posts at DZone. You can read more from them at their website. View Full User Profile

jQuery plugins with jsTestDriver

12.15.2011
| 5644 views |
  • submit to reddit
In this article we're going to develop an example of jQuery plugin with the aid of jsTestDriver, a little framework for writing automated tests.

jQuery plugins

Plugins in jQuery are simply functions added to jQuery.fn, which is the prototype of the objects produced by $(). As such, they will be bound to the current element returned by $(), where you will be able to call them.

The plugin refer with this as the current object where they are applied; this is usually a node list representing multiple elements. You can all a plugin with:
$('#elementId').pluginName();

As a rule of thumb, plugins should be defined in a closure to avoid accidentally polluting the global scope. Moreover, when they do not return a value, they should just return this to maintain jQuery's typical chainability.

jsTestDriver

jsTestDriver is a javascript testing framework. It captures browsers and makes them execute JavaScript code: after the capture, you can use it from the command line to repeatedly execute unit tests every time you add a test or implement a functionality.

This tool is able to simulate DOM nodes, by producing them on the fly and without needing to attach anything to the real document object. It's up to you to write code decoupled enough from the browser to be able to work without a real document (and I will show you how in this article.)

The example

We're going to write the jQuery maxHeight plugin example. Its purpose is to return the maximum height of a set of elements. For a minimal primer on how to setup jsTestDriver, refer to my article in the Want more? section.

We start with a minimal configuration, including just jQuery, our test and our source file:

server: http://localhost:4224

load:
- http://code.jquery.com/jquery-1.7.1.js
- src/*.js
- test/*.js

The test expects to be able to call maxHeight() on jQuery-powered nodes. When we create DOM nodes with jsTestDriver comments, they are subsequently available on this:

TestCase("maxHeightPluginTest", {
    'test returns the height of a DIV' : function () {
        /*:DOC divElement = <div style="height: 100px;"></div>*/
        assertEquals(100, $(this.divElement).maxHeight());
    }
});

The first implementation is just a Fake It example, in order for us to get a walking skeleton. The only complex code is the closure automatically called by passing jQuery, in order to preserve the global scope from the accidental introduction of variables:

(function ($) {
    $.fn.maxHeight = function() {
        return 100;
    }
})(jQuery);

Now we can add another test, that should break the current fake implementation:

TestCase("maxHeightPluginTest", {
    'test returns the height of a div' : function () {
        /*:DOC divElement = <div style="height: 100px;"></div>*/
        assertEquals(100, $(this.divElement).maxHeight());
    }, 
    'test returns the height of the current div' : function () {
        /*:DOC divElement = <div style="height: 200px"></div>*/
        assertEquals(200, $(this.divElement).maxHeight());
    }
});

And implement it:

(function ($) {
    $.fn.maxHeight = function() {
        return this.height();
    }
})(jQuery);

I think you get the basic cycle now: each test forces us to make the code a little more general.

The final result is this test case:

TestCase("maxHeightPluginTest", {
    'test returns the height of a div' : function () {
        /*:DOC divElement = <div style="height: 100px;"></div>*/
        assertEquals(100, $(this.divElement).maxHeight());
    },
    'test returns the height of the current div' : function () {
        /*:DOC divElement = <div style="height: 200px"></div>*/
        assertEquals(200, $(this.divElement).maxHeight());
    },
    'test returns the maximum height of multiple divs' : function () {
        /*:DOC container = <form>
            <div style="height: 100px"></div>
            <div style="height: 200px"></div>
            <div style="height:  50px"></div>
           </form>
         */
        var divs = $(this.container).children('div');
        assertEquals(200, divs.maxHeight());
    }
});

Which has driven this code to be written:

(function ($) {
    $.fn.maxHeight = function() {
        var max = null;
        this.each(function () {
            var currentHeight = $(this).height();
            max = Math.max(currentHeight, max);
        });
        return max;
    }
})(jQuery);

Want more?

The whole code sample is on Github.

I've written about jsTestDriver and how to generate DOM elements with it on this website.

There is an hour-long presentation available from the author of Test-Driven JavaScript development, Christian Johansen, where he develops the client side of Google search suggestions with TDD. The presentation involves a larger example than this one, including presenter objects and the stubbing of Ajax calls. If you commonly write JavaScript with cowboy coding as many of us do, I suggest you to watch it.

Published at DZone with permission of Giorgio Sironi, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Edgar Martinez replied on Mon, 2012/01/23 - 8:17pm

thanks great tutorial

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.