Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Practice exercises CHAPTER 3 127


FIGURE 3-21 he passing testT


  1. Modify the test by adding a loop to test all the number buttons. Rename the test to
    Button Click Test.
    Remember that you are appending to txtInput, so you need to test the last character
    to see whether you got the correct result. You should also add another assertion to
    the length of the string as you append to txtInput. Don’t forget that you added code
    to numberClick to remove leading zeros, and this loop starts by triggering btn0, so
    your assertion on the length must take that into account. Your test should look like the
    following:
    test("Button Click Test", function () {
    var buttonQuantity = 10;
    expect(buttonQuantity * 2);
    for (var i = 0; i < buttonQuantity; i++) {
    var btn = document.getElementById('btn' + i);
    QUnit.triggerEvent(btn, "click");
    var result = txtInput.value[txtInput.value.length-1];
    var expected = String(i);
    equal(result, expected, 'Expected value: ' + expected +
    ' Actual value: ' + result);
    var expectedLength = i < 2? 1 : i;
    equal(txtInput.value.length, expectedLength,
    'Expected string length: ' + expectedLength +
    ' Actual value: ' + txtInput.value.length);
    }
    });


This test sets the buttonQuantity variable to 10, and buttonQuantity calls the expect
function to set the quantity of assertions to expect. There are two assertions per but-
ton. The for loop executes 10 times to obtain a reference to the appropriate button,
trigger the click event, retrieve the result, perform an assertion that checks the last
character of txtInput, and perform an assertion that checks the length of txtInput.
Free download pdf