DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. JavaScript
  4. Testing JavaScript when the DOM gets in the way

Testing JavaScript when the DOM gets in the way

Giorgio Sironi user avatar by
Giorgio Sironi
·
Jul. 05, 11 · Interview
Like (0)
Save
Tweet
Share
24.61K Views

Join the DZone community and get the full member experience.

Join For Free

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');
div.appendChild(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>*/
assertNotUndefined(this.element);

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

Example

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 () {
        assertUndefined(this.inputElement);
        /*:DOC inputElement = <input id="searchbox" value="Type here" /> */
        assertNotUndefined(this.inputElement);
        assertEquals('Type here', this.inputElement.value);
    },
    'test that a DOM node can be scoped to a single test' : function () {
        assertUndefined(this.inputElement);
    },
    'test that a DOM node can be appended to the document' : function () {
        /*:DOC += <input id="appendedsearchbox" value="Type here" /> */
        assertNotNull(document.getElementById('appendedsearchbox'));
    },
    'test that an appended DOM node is not global anyway' : function () {
        assertNull(document.getElementById('appendedsearchbox'));
    },
    '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> */
        assertNotNull(document.getElementById('first'));
        assertNotNull(document.getElementById('second'));
    }
});
JavaScript Testing code style

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Spring Boot vs Eclipse Micro Profile: Resident Set Size (RSS) and Time to First Request (TFR) Comparative
  • Unlocking the Power of Elasticsearch: A Comprehensive Guide to Complex Search Use Cases
  • The 5 Books You Absolutely Must Read as an Engineering Manager
  • Multi-Cloud Integration

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: