-
Share DOM Fixtures between JavaScript Unit Tests - [Javascript]
2009-12-21
For the JavaScript unit tests that operate DOM, it's quite handy if the DOM fixtures could be shared between tests. This involves how to load another HTML file from one HTML file for most of the JavaScript testing frameworks (like Screw.Unit and JSUnit), the prior file is the DOM fixture and the later file hosts the test codes.
This blog demonstrates a way to do it through jQuery synchronized Ajax call. Below is the code skeleton of a test file:
<html> <head> <script type="text/javascript" src="lib/jquery-1.3.2.js"></script> </head> <body> <div id="fixture"> <script type="text/javascript"> $.ajaxSetup({ async: false }); // Ajax will run in sync $("#fixture").load("fixtures/DOMFixture.html"); // replace inner html with loaded content </script> </div> <script type="text/javascript"> // tests go here </script> </body> </html>This works for all the mainstream browsers including Firefox and IE.
Another possible approach that I haven't verified in detail is that 1) create XML document element dynamically, 2) load fixture file to the element synchronously, then 3) append the element to the place holder DIV in test file.
-
Code Snippet to Log All Events as They Are Triggered - [Javascript]
2009-04-28
I paired with Josh Price wrote the javascript code below, just before that we noticed something abnormal about event handling and wanted to find out what happened.
Just paste the code below into Firebug console of Firefox, run it, do something triggering events in page and watch the log printed out.
Please note that this requires jQuery.
var counter = 0; $("*").each(function() { var events = $(this).data('events'); if(events) { $.each(events, function(type, handlers) { $.each(handlers, function(i, handler){ handlers[i] = function(){ handler.apply(this, arguments); console.log(++counter, type); }; }); }); } });
You can add more logging per your need, e.g. the time used for each handler call. -
A Quick Check of Javascript Code Quality - [Javascript]
2009-03-30
Here is the way we used today checking the quality of client side javascript code.
Launch Firefox, access the site under developing, open Firebug console and run the scripts below:
for(var property in window){ console.log(property); }
We get a list of properties directly defined in window instance, which is the place where all global functions and variables exist.Filter out the build in properties and the ones introduced by the external libs, like jQuery, Prototype, and we get all the global functions and variables defined by the team.
Then ask:
- Do we have too many of them and is it a sign of lacking encapsulation?
- Are all of them worth being introduced with global accessibility?
We really got some clues of refactoring, cool!The key is that try object oriented javascript before the plain global functions and variables run out of control.
- Do we have too many of them and is it a sign of lacking encapsulation?