DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Frameworks
  4. jQuery plugins with jsTestDriver

jQuery plugins with jsTestDriver

Giorgio Sironi user avatar by
Giorgio Sironi
·
Dec. 15, 11 · Interview
Like (0)
Save
Tweet
Share
8.31K Views

Join the DZone community and get the full member experience.

Join For Free
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.

JQuery unit test code style

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Important Data Structures and Algorithms for Data Engineers
  • [DZone Survey] Share Your Expertise and Take our 2023 Web, Mobile, and Low-Code Apps Survey
  • 10 Easy Steps To Start Using Git and GitHub
  • Introduction to Automation Testing Strategies for Microservices

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: