Wednesday, June 11, 2008

Detecting javascript errors with selenium

I've only found out how to do this by including a few javascript functions that get included in the code. I have made no attempt to remove this from production code:


window.onerror = function(){
if (sessionStorage){ // Mozilla only
var cnt;
if (sessionStorage.errcnt){
cnt = parseInt(sessionStorage.errcnt);
} else {
cnt = 0;
}
cnt++;
sessionStorage.errcnt = cnt;
}
return false;
}

function hadJavaScriptError(){
if (sessionStorage){ // Mozilla only
if (sessionStorage.errcnt){
delete sessionStorage.errcnt;
return true;
}
}
return false;
}
Somewhere in your selenium test you can put this check:
String hadJserror = getSelenium().getEval("window.hadJavaScriptError()");
assertFalse("Page had a javascript error, this error has occured somewhere during the test.", Boolean.parseBoolean(hadJserror));


I've put this straight after a common waitForPageToLoad function that we are using, please note that if you do so, it must be after the call to waitForPageToLoad.

Note that the javascript code uses mozilla session store (and probably IE8) to actually keep a persistent count of javascript errors. I'm sure some "userData" for IE could be used for older IE versions

No comments:

Post a Comment