Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing jQuery document.ready function

I have a question in regards to unit testing jQuery's document.ready function().

Currently I have 2 scenarios in my code:

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

And:

$(document).ready(function()
{
    // some really long setup code here
});

I tried to write a unit test for the first scenario, but I just couldn't get it to run into the document.ready function. As for the second scenario, I haven't come up with a way to test it yet (I'm having trouble coming up with both a way to test it and the syntax).

So assuming I cannot change the source code, are there any ways to test those functions? (assuming it is a good idea to test them)

Thanks.

like image 560
BeraCim Avatar asked Nov 26 '09 00:11

BeraCim


1 Answers

You do not need to test $(document).ready as it is part of the framework and is already unit tested. When writing unit tests you need to test two things:

  1. Your interaction with the framework. This includes things like making sure that you call the right functions with the right parameters.
  2. Your own code - that your code does the right thing.

So what you really need to do is to make sure that whatever code that gets called from $(document).ready is correct.

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

All you need to do now is to unit test myInit function.

What you can also do is mock out $.ready function to make sure that you are calling it:

var readyCalled = false;
$.ready = function(func){
  readyCalled = (myInit == func);
}

//Your code containing `myInit` will get executed somewhere here
//....
//Then test:
test("Should have called ready", function() {
 ok(readyCalled, "ready should have been called with myInit as a parameter.")
});
like image 95
Igor Zevaka Avatar answered Sep 29 '22 07:09

Igor Zevaka