I would like to use the selenium2 c# webdriver to test our login mechanism. The following test passes if I run through it in debug mode and give the Click method some time. If I run it normally though the test fails with a NoSuchElementException.
[Test]
public void TestClickLogonLink()
{
_driver.Navigate().GoToUrl("http://nssidManager.local/");
IWebElement loginElement = _driver.FindElement(By.Id("loginWidget"));
IWebElement logonAnchor = loginElement.FindElement(By.LinkText("Log On"));
logonAnchor.Click();
IWebEle开发者_开发技巧ment userNameTextBox = _driver.FindElement(By.Id("UserName"));
Assert.IsNotNull(userNameTextBox);
}
How do I need to tell Selenium to Wait until the logonAnchor.Click has finished loading the next page?
Set the implicit wait like so:
driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0,30));
This will allow Selenium to block until the FindElement succeeds or times out.
I usually have some extensions methods for the driver:
public static class SeleniumDriverExtensions
{
public static void GoToUrl(this IWebDriver driver, string url, By elementToWaitFor = null)
{
driver.Navigate().GoToUrl(url);
driver.WaitUntillElementIsPresent(elementToWaitFor ?? By.CssSelector("div.body"));
}
public static void WaitUntillElementIsPresent(this IWebDriver driver, By by)
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(d => d.IsElementPresent(by) && d.FindElement(by).Displayed);
}
.....
}
I have div.body on all my pages.
I've made the following extension method to the IWebElement class:
public static void ClickAndWaitForNewPage(this IWebElement elementToClick, IWebDriver driver)
{
elementToClick.Click();
new Wait(driver).Until(d => elementToClick.IsStale(), 5);
}
private static bool IsStale(this IWebElement elementToClick)
{
try
{
//the following will raise an exception when called for any ID value
elementToClick.FindElement(By.Id("Irrelevant value"));
return false;
}
catch (StaleElementReferenceException)
{
return true;
}
}
精彩评论