I am writing some tests in selenium webdriver (on node.js). and have made a custom function to check the css value of an iFrame Element. I'm a coding beginner.
The script tests an app where the user writes the image width they want (just putting in a number) and the image in an iFrame should change width. This is tricky because one must switch iFrames, wait for elements to become stale (as the new image width is loaded) then grab the new element and check its css value.
Often, the tests are flaky because sometimes it checks before the value has changed etc. I finally wrote a function that passed 120 times out of 120 times.
//function looks for 'el', then switches iframe and extracts the desired cssValur, then compares it to the 'value' we expect
Page.checkCssValue = function (el, cssValue, value){
//find function, the '0' represents the iframe index
var newEl = this.find(el, 0);
return newEl.getCssValue(cssValue).then(function(result){
if(result !== value){
console.log(result + " and " + value + " Do not Match.")
return Page.checkCssValue(el, cssValue, value);
}
else{
console.log(result + " and " + value + " Do Match!")
return result;
}
});
};
But I'm not sure if this is considered bad programming and if a while loop would be better?
a recursion can lead to a stack overflow because there is no tail-call optimization without "strict"
I wouldn't say it a poor use of recursion at all. But as @chilimatic has put it, unless you're using ES6's tail call optimisation feature, I'm afraid the elegance of recursion could be out-trumped by a stack overflow.
The maximum stack size varies across different versions of NodeJS, and different browsers. You could run the following function (thanks to Dr. Axel) to find out an estimate for your JS environment. This is indeed just an estimate, as this number would vary depending on the size of frames in the stack.
function computeMaxCallStackSize() { try { return 1 + computeMaxCallStackSize(); } catch (e) { // Call stack overflow return 1; } } // For Node v6.9.4, the following line outputs 15718. console.log(computeMaxCallStackSize());If you are certain that your use case would never go anywhere remotely near the number estimate of your JavaScript environment, then by all means use recursion; else, I would suggest to go for a loop implementation.
Also, did you mean to write
return Page.checkCssValue(newEl, cssValue, value);on line 8?As an aside; if you want to implement tail call optimisation (TCO) yourself, (or you are interested in how it is implemented) do read about the trampoline pattern for TCOs.