Agile Zone is brought to you in partnership with:

I am a programmer and architect (the kind that writes code) with a focus on testing and open source; I maintain the PHPUnit_Selenium project. I believe programming is one of the hardest and most beautiful jobs in the world. Giorgio is a DZone MVB and is not an employee of DZone and has posted 638 posts at DZone. You can read more from them at their website. View Full User Profile

Testing JavaScript when the DOM gets in the way

  • submit to reddit

It's one thing to exercise a simple function or even an object graph in a controlled environment; it's another to assert the DOM is manipulated correctly: usually inside a test suite window.document is an empty one, and is shared between tests.

For example, the classical approach to JavaScript testing (JsUnit) lead to pages full of HTML, which executed lots of tests one after the other and show a green or red bar; there's a lot of room for improvement.

Step 0: mock as much as possible

Test Doubles exist in JavaScript too: you're not forced to call the problematic functions which manipulate the DOM or create an XMLHttpRequest. You can harness Test Double in two ways.

The first is the dynamic substitution of functions:

var oldCreateElement = {};
myLibrary.createElement = function() {
    this.called = true;
    this.arguments = arguments;
// test code where production code will call myLibrary.createElement...
myLibrary.createElement = oldCreateElement;

The second is via injection: the myLibrary object is passed to the constructor or to a setter of the object under test. That's really similar to all other DI implementations in Java and PHP.

I advise you to only substitute part of your code with these techniques, due to the Only mock types you own principle.

Step 1: avoid reporting through the browser

When a testing framework uses a browser page for reporting, the DOM of that page would have two uses: provide fixtures for the tests and production code to work on, and reporting to the end user.

Another approach, followed by jsTestDriver, is to report through the console: you execute tests via a command line or with an IDE plugin. The browser is captured and used to execute the code, but does not show results: it sends them back via Ajax to the jsTestDriver server.

The result is that you can start execution from anywhere, and that you can tear apart the blank document in a test without breaking the framework functionalities.

Step 2: avoid programmatic creation of DOM elements

Once in a while you will need some elements for your code to act on. Even if you stub out the code that works on the DOM, you will still have to test it somewhere, or to run functional tests which involve a large group of objects.

If you want to create the HTML elements by hand, this is what you're destined to:

this.div = document.createElement('div');
var p = document.createElement('p');
p.innerHTML = "bar"; = 'foo';

It's boring to read (and to write), noisy and difficult to understand. Maybe can be shortened with jQuery or other libraries, but jsTestDriver's solution is really compact: it involves inlining HTML code as a declaration.

From the jsTestDriver docs, we see one of the special comments that are interpreted for HTML elements creation:

/*:DOC element = <div><p>foo</p></div>*/

Now that we know how the various steps work, let's dive into the code.


The two options for creating DOM nodes in jsTestDriver are:

  • creating snippets of HTML; the root element is grabbed and a reference is put on this for further use.
  • appending HTML to the real document, if the production code is calling document or window to grab the elements itself. Of course you should try to limit these calls as much as possible for the sake of easy-test-in-isolation, but your libraries may call them (and jQuery, or ExtJS, will.)

Here is a complete jsTestDriver test case which shows you the functionalities at your disposal.

TestCase('tests that involve the DOM', {
    'test that a DOM node created for this test exists' : function () {
        /*:DOC inputElement = <input id="searchbox" value="Type here" /> */
        assertEquals('Type here', this.inputElement.value);
    'test that a DOM node can be scoped to a single test' : function () {
    'test that a DOM node can be appended to the document' : function () {
        /*:DOC += <input id="appendedsearchbox" value="Type here" /> */
    'test that an appended DOM node is not global anyway' : function () {
    'test that HTML code can span over multiple lines' : function() {
        /*:DOC anotherBox = <input id="anotherbox" 
                                value="Some default" /> */
        assertEquals('Some default', this.anotherBox.value);
    'test multiple top-level nodes can be appended' : function() {
        /*:DOC += <div id="first"></div>  
                  <div id="second"></div> */
Published at DZone with permission of Giorgio Sironi, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)


Mister Pink replied on Tue, 2011/07/05 - 1:38pm

Asserting on the DOM is painful in unit tests! Sometimes it is even inadequate:

On a page with very dyamic content, unit tests are not sufficient, your really need to make assertions for testing purposes in the running code.

 For this purpose I started QAssert (

It is ment to do stuff like:



 If an assertions fails it logs this fact to the console, and more importantely, it reports it via AJAX to a pre-configured URL (with a stacktrace).

This way automated and manual tests can catch way more bugs on the page!(Assertion calls can default to no-op or can be completely removed during minification.)

Giorgio Sironi replied on Tue, 2011/07/05 - 5:10pm in response to: Mister Pink

Nice to see that JavaScript tools are maturing. However the purpose of the method presented here is to setup some DOM nodes for code that strictly requires them for manipulation.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.