HTML and CSS Reference
In-Depth Information
The element object is a simple stub object. At this point there's no need to
use a real DOM element, because all we want to check is that some property was
assigned.
The test fails, and Listing 15.8 assigns the class name to pass it.
Listing 15.8 Adding the class
function setView(element) {
element.className = "js-chat";
}
At this point you might worry about a few things. Should we really be overriding
the class name like that? Should the class name not be configurable? Remember:
You ain't gonna need it! At this point, we have no use case demonstrating the need
to use an element that already has class names or the need to use another class
name than “js-chat.” Once we have, we can jot down a few tests to document those
requirements, and then we can implement them. Right now we don't need them,
and they'll just be slowing us down.
15.2.1.3 Adding an Event Listener
Next we will add an event listener to the form's “submit” event. To do this, we
will use the tddjs.dom.addEventHandler interface we wrote in Chapter 10,
Feature Detection. Testing event handlers is commonly accepted as a challenging
task. The main reasons being that triggering user events from script in a cross-
browser manner is less than trivial, and tests need a lot of setup, thus they can easily
become complex.
Unit testing event handlers in application code, when done right, is in
fact trivial. Attaching event handlers through an abstraction such as tddjs.
dom.addEventHandler means that all we need to assert is that this method
is called correctly. By stubbing it, we gain access to the arguments passed to it,
which means that we can manually call the handler to test the behavior of the event
handler (in another dedicated test case). Tests that rely heavily on event data, such as
mouse coordinates, neighbouring elements, and less tangible data may require com-
plex setup, but such setup can be hidden behind, e.g., a fake event implementation
for use in tests.
I'm not saying that you should not test event handlers end-to-end, but I am
saying that the application unit test suite is unlikely the right place to do so. First,
one would hope that whatever library is being used to add event listeners has its
own comprehensive test suite, meaning that in your tests you should be able to
trust it. Second, if your application has acceptance tests, or some kind of in-browser
 
Search WWH ::




Custom Search