Testing JavaScript when the DOM gets in the way

DZone 's Guide to

Testing JavaScript when the DOM gets in the way

· Agile Zone ·
Free Resource

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";
div.id = '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> */

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}