I want to make sure that an element is present before the webdriver starts doing stuff.
I\'m trying to get something like this to work:
WebDriverWait w
Inspired by Loudenvier's solution, here's an extension method that works for all ISearchContext objects, not just IWebDriver, which is a specialization of the former. This method also supports waiting until the element is displayed.
static class WebDriverExtensions
{
///
/// Find an element, waiting until a timeout is reached if necessary.
///
/// The search context.
/// Method to find elements.
/// How many seconds to wait.
/// Require the element to be displayed?
/// The found element.
public static IWebElement FindElement(this ISearchContext context, By by, uint timeout, bool displayed=false)
{
var wait = new DefaultWait(context);
wait.Timeout = TimeSpan.FromSeconds(timeout);
wait.IgnoreExceptionTypes(typeof(NoSuchElementException));
return wait.Until(ctx => {
var elem = ctx.FindElement(by);
if (displayed && !elem.Displayed)
return null;
return elem;
});
}
}
var driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://localhost");
var main = driver.FindElement(By.Id("main"));
var btn = main.FindElement(By.Id("button"));
btn.Click();
var dialog = main.FindElement(By.Id("dialog"), 5, displayed: true);
Assert.AreEqual("My Dialog", dialog.Text);
driver.Close();