Testing Javascript that Manipulates the DOM

Viewed 6142

I've been looking into javascript test suites and I have found QUnit to be very interesting. I understand how to test computational code, but...

How do you test javascript applications written primarily for DOM manipulation?

it seems like testing the position/color/etc of DOM elements would be a moot point because you'd end up doing somethign like this:

$("li.my_element").css("background-color", "#f00");

and then in your test...

$(function() {
    module("coloring");
    test("test_my_element", function() {
        var li_element_color = $("li.my_element").css('background-color');
        equals(li_element_color, "#f00");
    });
});

this just doesn't feel right because it basically just doing this:

var my_li= $("li.my_element");
my_li.css("background-color", "#f00");
if ( my_li.css("background-color") == "#f00" ) {
    return true;
}

Am I nuts? How is this supposed to be done?

edit: the heart of the question:

I guess what I'm getting at is, I need to make sure the code isn't broken before I deploy, but the vast majority of it is UI helpers and ajax. How do I test that things are appearing correctly?

A few examples:

  • test that a JQuery UI dialog is appearing on top of all other elements
  • test that the drag-n-drop is working properly
  • test that the color of a droppable changes when an element is dropped on it
  • test that the ajax is all working properly
  • test that there are no extraneous commas that will break IE
5 Answers

I test AJAX stuff like this:

  1. Make the AJAX call
  2. Set up a JavaScript timer
  3. Check the DOM to see if the expected changes have happened

Now, it could be that the AJAX call hasn't returned before you do your check, but this is also useful test information; with an AJAX call, there is (usually) some time after which we'd call it a failure. As an example, if we're doing a suggestion popup, and it's taken 30 seconds to come back, that's a fail.

Related