Monkey Patching JQuery’s Append and Insert Functions

If you have some DOM manipulation code using JQuery and you want to test it using unit tests, you will, most probably, want to test your code in isolation, meaning you don’t actually want to modify the DOM in your tests. What you want to test is that the append and insert functions where called. For this you can “monkey patch” the JQuery functions as follows:

var originalAppend = $.prototype.append,
appendCalls = 0;

$.prototype.append = function () {
    appendCalls = appendCalls + 1;
};

// Testing code
ASSERT(appendCalls, 1);

// This is really important! Don't forget to restore
// the original append implementation.
$.prototype.append = originalAppend;

The “operation” is very similar for insertBefore function:

var originalInsert = $.prototype.insertBefore,
insertCalls = 0;

$.prototype.insertBefore= function () {
    insertCalls = insertCalls + 1;
};

// Testing code
ASSERT(insertCalls, 1);

// This is really important! Don't forget to restore
// the original insert implementation.
$.prototype.insertBefore= originalInsert;

Note that this solution works if you don’t want to add additional dependencies to your project. If you think it’s worth the effort you can use a fancier unit testing framework that actually supports monkey patching and handles the “restoration” of the original function after each test.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s