DefaultWait has got to be one of the most useful classes in Selenium WebDriver!

Hackered
Tuesday, July 1, 2014
by Sean McAlinden

Recently I have been working with Selenium WebDriver a great deal and I am a real fan, it is an amazing piece of kit, however...

There seems to be a big gotcha when using Selenium WebDriver, you need to slow it down and give it a little programmatic patience.

Slow it down!

Ok, this does sound remarkably like a terrible idea however it is a necessary fact as Selenium will often check for an element just before the browser has had chance to add it to the DOM and... boom.

Don't panic!

Introducing the DefaultWait class: an awesome class for gracefully waiting for elements to be ready.

 

The following represents an extension I use for consuming this class:

public static IWebElement WaitUntil(this IWebElement element, Func<IWebElement, bool> condition)
{
    IWait<IWebElement> wait = new DefaultWait<IWebElement>(element);
    wait.Timeout = TimeSpan.FromSeconds(10);
    wait.PollingInterval = TimeSpan.FromMilliseconds(500);
    wait.Until(condition);
    return element;
}

The following is an example of how I consume this helper:

myWebElement.WaitUntil(e => e.Displayed).SendKeys("Some Text");

So the above example will poll 10 times every 500 milliseconds until the element is displayed, otherwise it will timeout.

 

This is definitely one of my favourite classes from the Selenium team... nice work.