Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1
Lesson 2: Writing, testing, and debugging JavaScript CHAPTER 3 93

<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
<div id="qunit-fixture">test markup, will be hidden</div>
</body>
</html>

Now write the first test. When using TDD, always write the test first, run it to see the test
fail, and then add code to make the test pass. In the tests.js file, add the following test to see
whether a greeting variable contains Hello World:
test("A Hello World Test", 1, function () {
equal(greeting, "Hello World", "Expect greeting of Hello World");
});

Here is an overview of what’s happening with this code. The code is calling a test function,
which is included in the QUnit source code. A function is a block of code that you can call to
perform one or more actions. The test function requires three parameters. The first parameter
is a freeform description of the test, which is A Hello World Test. The description of the test is
displayed in the QUnit summary screen when you run the tests. The second parameter, which
has a value of one, represents the quantity of assertions that you expect to perform within
the test function. The third parameter is an anonymous function. An anonymous function is
a block of code that has no name and can perform one or more actions. This is where you
add any code to execute, and then you perform assertions to verify that the test is successful.
In this anonymous function, the equal function is being called to see whether the greeting
variable contains Hello World. The equal function takes three parameters. The first parameter
is the actual value, in this case, the greeting variable. The second parameter is the expected
value, Hello World. The third parameter is a message that you want to display, in this case,
Expect Greeting Of Hello World.
Because you have not created a greeting variable, this test should fail. When you run the
tests (click Debug and choose Start Debugging), you should see the failed test with a red
indicator. Figure 3-6 shows the QUnit summary screen with the failed test.
The test failed with a message that states that “greeting” is undefined. Now, to make the
test pass, add the following code, which declares a greeting variable and assigns a value of
Hello World in the default.js file:
var greeting = 'Hello World';

Key
Te rms

Free download pdf