Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing "unit testable" jQuery code?

Up untill now I was used to write all my code inside the ready() function like:

$(document).ready(function() {
  // all my code
});

Now I see that with this approach, my code is not "unit testable", e.g. I cannot access the stuff inside ready() from QUnit.

What is the proper way to structure jQuery code that is compatible with using the ready() function and able to be tested?

Is there a good open source code base or project to study and learn from?

like image 436
Asimina Pappas Avatar asked Aug 16 '11 14:08

Asimina Pappas


1 Answers

Have your code in the ready handler just calling functions outside of the ready handler:

$(document).ready(function() {
  // call some functions outside of handler
});

// most of my code

That way, you can call those functions for unit testing as well.


NB, there's a short-cut for $(document).ready:

$(function() {
  // call some functions outside of handler
});

// most of my code
like image 148
Spycho Avatar answered Oct 17 '22 08:10

Spycho