navigation
 Thursday, August 16, 2007

One of the problems we've encountered while using Selenium to execute automated tests feels like it's related to timing, and that's when we use the "IsElementPresent" method followed immediately by a command to get the contents in that element. The results are very intermittent - sometimes, even when we KNOW that there should be something there, we're unable to find it, almost like the element started getting rendered, but didn't get populated yet.

The problem, then, is that when you expect that there's going to be data there, it would be nice to make sure that there actually is before you read it, try to convert it or match it, and throw an error. That's where WaitForCondition comes in. Basically, this is a javascript call that returns a true/false value. THe references to it in the documentation are tantalizing, but not very specific. After some research, I found how to make it work for me. Here's the relevant code:

1
2
3
4
5
6
7
    public class Utilities
{
static public void WaitForCondition(string script, string timeout)
{
selenium.WaitForCondition(script, timeout);
}
}
And then in the test code:

1
2
const string ELEMENT_HAS_LENGTH = "var value = selenium.getText('{0}'); value.length > 0;";
Utilities.WaitForCondition(String.Format(ELEMENT_HAS_LENGTH, "ctl00_cphContents_ode_ddlPrices"), "10000");
 
The way this works is that the id of the control we want to be checked is passed in to the constant string containing the script, and formatted with the control's id. Next, the little snippet of javascript gets executed. The control is located on the page (if it's not there, it gets assigned a null), and then gets evaluated to see if the length of the text associated with the control is longer than zero. If it's not, the result is false, and (I assume) the selenium engine waits for some predetermined length of time before the script snippet executes again. This continues until either the condition evaluates as true, or the timeout (expressed in milliseconds) expires.

Pretty easy, once you understand the necessary format of the javascript snippet.