I am following a tutorial and I took the URL from there to try to learn Implicit wait on it. I wrote the below code to click the button on page and then wait 30 seconds for the new element to be visible, before taking the text from the element and confirming it with Assert. The code works fine when i debug but running the test results in failure and the test is also finished in just 6.8 seconds.
driver.Navigate().GoToUrl("https://the-internet.herokuapp.com/dynamic_loading/1");
driver.FindElement(By.XPath("//*[@id='start']/button")).Click();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30);
string text = driver.FindElement(By.Id("finish")).Text;
Assert.AreEqual("Hello World!", text);
ImplicitWait is not that effective when interacting with dynamic elements. Instead you need to replace implicit wait with explicit wait.
As an example, to retrieve the text from the element you have to induce WebDriverWait for the ElementIsVisible()
and you can use either of the following Locator Strategies:
Id
:
string text = new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementIsVisible(By.Id("finish"))).Text;
Assert.AreEqual("Hello World!", text);
CssSelector:
string text = new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementIsVisible(By.CssSelector("div#finish"))).Text;
Assert.AreEqual("Hello World!", text);
XPath:
string text = new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementIsVisible(By.XPath("//div[@id='div#finish']"))).Text;
Assert.AreEqual("Hello World!", text);