Web Development

Testing Browser Apps

By Andy Sylvester, November 26, 2012

The QUnit framework makes it easy to test Web apps directly in the browser. By showing the red/green results in the browser with links to the failing tests, it makes it possible to write, test, and correct quickly.

Add Tests for Text Field/Button Part of Hello World Example

Now that you have seen some examples of algebraic tests, let's move on to using QUnit to perform tests of DOM elements. A useful feature of QUnit is the ability to add test HTML that your tests can use to the page. QUnit uses a div with an ID of "qunit-fixture" to designate the test HTML code. An example might look like this:

In this modified function, logic has been added to save the HTML element with the ID of qunit-fixture to a variable, and to extract the HTML within that element. A new type of test was added ("equal") that compares the actual and expected values of the item being tested, along with the description of what the test is doing. Here is what the new file looks like (save as qunittest03.html):

As you can see, the new test fails and a red area is shown in the part of the page with the test results. Looking at the results, it appears that when the data within the div element is extracted, a quotation mark is added for each carriage return. Let's try making a change in the "qunit-fixture" test HTML code to see whether that has an effect. Put all of the logic on one line, making it look like this:

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task.
However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Video

This month's Dr. Dobb's Journal

This month,
Dr. Dobb's Journal is devoted to mobile programming. We introduce you to Apple's new Swift programming language, discuss the perils of being the third-most-popular mobile platform, revisit SQLite on Android
, and much more!