Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Practice exercises CHAPTER 3 125


<button id="btnClearEntry">CE</button><br />
<button id="btnPlus">+</button>
<button id="btnMinus">-</button>
</div>
</body>
</html>


  1. Right-click the CalculatorTests.html file and choose Set As Start Page.
    It’s time to add the first test. The goal of the test is to add a 5 in the txtInput text box
    when btn5 is clicked. Btn5 is arbitrarily picked, which doesn’t matter because you will
    add code to make all the buttons work. The QUnit object has a trigger method event
    that can be used to simulate a click on btn5. In the tests.js file, add the following test:
    test("Btn5 Click Test", function () {
    expect(1);
    var btn = document.getElementById('btn5');
    QUnit.triggerEvent(btn, "click");
    var result = txtInput.value;
    var expected = '5';
    equal(result, expected, 'Expected value: ' + expected + ' Actual value: ' +
    result);
    });
    In the previous code example, a txtInput variable is being referenced, but the variable
    hasn’t been declared.

  2. In the CalculatorLibrary.js file, add a statement that declares the variable and an
    initialize function that can be called when each test is run but will be called by the
    default. html page when it runs the finished code.

  3. In the initialize function, add a statement that locates the txtInput text box and assign
    the result to the txtInput variable. Your code should look like the following:
    var txtInput;


function initialize() {
txtInput = document.getElementById('txtInput');
}

You must modify the tests.js file to call the initialize function as part of a setup function
that will run before each test function. Do this by defining a module at the top of the
tests.


  1. Add the following code to the top of the tests.js file:
    module('Calculator Test Suite', { setup: function () { initialize(); } });


The first parameter of the module definition is the name of the module. The second
parameter defines an object that has a setup property. The setup property is assigned
a function expression that calls the initialize function before each test.
Free download pdf