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:
<div id="qunit-fixture"> This is a test </div> <!-- qunit fixture markup -->
To show how this works, let's add some additional logic to the testing function to check the text in the fixture HTML.
test("hello", function() { // Find element with id="qunit-fixture" var testMessage = document.getElementById("qunit-fixture"); var testMessageresult = testMessage.innerHTML; ok(2 + 2 == 4, "two plus two equals four"); ok(2 + 5 == 7, "two plus five equals seven"); ok(5 + 5 == 10, "five plus five equals ten"); equal(testMessageresult, "This is a test", "text in div is correct"); });
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):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <link rel="stylesheet" href="qunit.css"> <script src="qunit.js"></script> <script> test("hello", function() { // Find element with id="qunit-fixture" var testMessage = document.getElementById("qunit-fixture"); var testMessageresult = testMessage.innerHTML; ok(2 + 2 == 4, "two plus two equals four"); ok(2 + 5 == 7, "two plus five equals seven"); ok(5 + 5 == 10, "five plus five equals ten"); equal(testMessageresult, "This is a test", "text in div is correct"); }); </script> <h1 id="qunit-header">QUnit Hello World</h1> <h2 id="qunit-banner"></h2> <ol id="qunit-tests"></ol> <div id="qunit-fixture"> This is a test </div> <!-- qunit fixture markup -->
When this HTML file is loaded, the results in Figure 3 appear:
Figure 3.
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:
<div id="qunit-fixture">This is a test</div> <!-- qunit fixture markup -->
When this change is added to the app, the test results now look like Figure 4:
Figure 4.