Javascript – How to invoke $(document).ready(function() {}) in unit testing

javascriptjqueryunit testing

I'm experiencing difficulties trying to invoke document.ready( function() {}) in my unit tests. Suppose I have multiple of them in my javascript file, and one of them called inside a named function i.e.

function myFunction() {
    $(document).ready(function() {
        //...
    });
}

How do I actually invoke them in my unit tests so I can actually test them? I'm using JsTestDriver to unit test my javascripts.

Thanks.

Best Answer

If it's a unit test, I'm guessing you check the function outputs when given certain inputs?

Here's my opinion:

You should prepare for the case where document.ready is called and the case where it isn't.

So your unit test should run each function twice - once to simulate a pre-ready call and one to simulate a post-ready call. That is, you should have one run-through where anything that happens on document.ready DOES run, and one run-through where it's just ignored (presumably to be called later on in the lifecycle).

EDIT: Just reread the question and understood it a bit more. You could just override $(document).ready to do what you want it to (which is NOT to wait for the DOMLoaded event to fire, but instead to run the functions immediately). This snippet will replace the $(document).ready function with a function that does exactly that. It should run before any unit tests.

var postReady = true; // or false to ignore the function calls.
jQuery.fn.ready = function(fn)
{
    if(postReady && fn) fn();
}

Example test case:

<html><head><title>whatever</title>
    <script type="text/javascript" src="/JS/jquery-1.3.2.js"></script>

    <script type="text/javascript">
        var postReady = true; // or false to ignore the function calls.
        jQuery.fn.ready = function(fn)
        {
            alert("We stole ready!");
            if(postReady && fn) fn();
        }

        $(document).ready(function()
        {
            alert("The function is called.");
        });
    </script>
</head><body></body>
</html>