Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

130 CHAPTER 3 Getting started with JavaScript


txtInput.value = '10';
QUnit.triggerEvent(btnClearEntry, "click");
var expected = '0';
equal(txtInput.value, expected, 'Expected value: ' + expected +
' Actual value: ' + txtInput.value);
});


  1. Press F5 to run the test and verify that the test fails because you haven’t subscribed to
    the click event of btnClearEntry.

  2. In the initialize function, add code to subscribe to btnClearEntry and call the clearEntry
    function. Add the clearEntry function with code to reset txtInput to zero.
    Your code should look like the following:
    function initialize() {
    for (var i = 0; i < 10; i++) {
    document.getElementById('btn'+i).addEventListener('click', numberClick,
    false);
    }
    txtInput = document.getElementById('txtInput');
    txtResult = document.getElementById('txtResult');


document.getElementById('btnPlus')
.addEventListener('click', plusClick, false);
document.getElementById('btnMinus')
.addEventListener('click', minusClick, false);
document.getElementById('btnClearEntry')
.addEventListener('click', clearEntry, false);
}

function clearEntry() {
txtInput.value = '0';
}


  1. Press F5 to run the test, which should pass.
    When btnClear is clicked, the value in txtInput and txtResult will be set to zero.

  2. In the tests.js file, add a new test to check btnClear when it’s clicked.
    Your test code should look like the following:
    test("Clear Test", function () {
    expect(2);
    txtInput.value = '10';
    txtResult.value = '20';
    QUnit.triggerEvent(btnClear, "click");
    var expected = '0';
    equal(txtInput.value, expected, 'Expected value: ' + expected +
    ' Actual value: ' + txtInput.value);
    equal(txtResult.value, expected, 'Expected value: ' + expected +
    ' Actual value: ' + txtResult.value);
    });

  3. Press F5 to run the test and verify that the test fails because you haven’t subscribed to
    the click event of btnClear.

Free download pdf