Clicking the buttons in QUnit functional testing with JQuery
I avoided using JQuery in my test pack for as long as I could, to try and learn a little about JavaScript the hard way. But I just could not get my button clicking test working cross browser. But clever JavaScript ninjas invented libraries like JQuery to help with exactly that type of problem so...
I wrote the previous posts in this series over on EvilTester:
- Test Driven JavaScript using QUnit
- Test Driven JavaScript Code Coverage using JSCoverage
- Functional testing JavaScript with QUnit - initial steps
In this post I shall use JQuery to 'click' on a button. So that I can 'functionally test' the button click side-effects. I have a button on my GUI which I want to click and make sure the side-effects of calling the function attached to that button display the results I expect on screen:
<button id="CheckForEPrimeButton" onclick="processInputText();">Check For E-Prime</button>
The following code only works in IE and generates a click event to trigger my button:
test("process eprime text by clicking on button",function(){
expect(3); document.getElementById("inputtext").value=
"Surely and \nIsn't this being" + " some bad text or rather Bob's WASn't he's being good"; var clickevent=document.createEvent('MouseEvents') clickevent.initEvent('click', true, true) document.getElementById("CheckForEPrimeButton").dispatchEvent(clickevent) equals(document.getElementById("wordCount").innerHTML,
15,"displayed wordCount = 15"); equals(document.getElementById("discouragedWordCount").innerHTML,
4,"displayed discouragedWordCount = 4"); equals(document.getElementById("possibleViolationCount").innerHTML,
2,"displayed possibleViolationCount = 2"); });
Sadly it fails in FireFox, but when I introduce the JQuery
test("process eprime text by clicking on button using JQuery",function(){ expect(3); document.getElementById("inputtext").value=
"Surely and \nIsn't this being" + " some bad text or rather Bob's WASn't he's being good"; $("#CheckForEPrimeButton").click();
equals(document.getElementById("wordCount").innerHTML,
15,"displayed wordCount = 15"); equals(document.getElementById("discouragedWordCount").innerHTML,
4,"displayed discouragedWordCount = 4"); equals(document.getElementById("possibleViolationCount").innerHTML,
2,"displayed possibleViolationCount = 2");
});
Voila, cross-browser functional testing and less code to boot.
