Practice exercises CHAPTER 3 129
function plusClick() {
txtResult.value = Number(txtResult.value) + Number(txtInput.value);
}
- Press F5 to run the test, which should pass.
When btnMinus is clicked, the value in txtInput will be subtracted from the value in
txtResult. - In the tests.js file, add a new test to check btnMinus when it’s clicked.
Your test code should look like the following:
test("Subtract Test", function () {
expect(1);
txtInput.value = '10';
txtResult.value = '20';
var btnMinus = document.getElementById('btnMinus');
QUnit.triggerEvent(btnMinus, "click");
var expected = '10';
equal(txtResult.value, expected, 'Expected value: ' + expected +
' Actual value: ' + txtResult.value);
}); - Press F5 to run the test and verify that the test fails because you haven’t subscribed to
the click event of btnMinus. - In the initialize function, add code to subscribe to btnMinus and call the minusClick
function. Add the minusClick function with code to subtract txtInput from txtResult.
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);
}
function minusClick() {
txtResult.value = Number(txtResult.value) - Number(txtInput.value);
}
- Press F5 to run the test, which should pass.
When btnClearEntry is clicked, the value in txtInput will be set to zero. - In the tests.js file, add a new test to check btnClearEntry when it’s clicked.
Your test code should look like the following:
test("Clear Entry Test", function () {
expect(1);