1

Hi I am checking that the text in an element to ensure its displaying the expected text..

The test fails as it says it returns "" but when I run it in debug it gets the correct text. I have added in a thread.sleep(5000) and this fixes the test (im not sure why?) and gets the displayed text but is there a better way of doing it as id prefer not to use sleep if possible.

IWebElement panel = _driver.FindElement(By.Id(currentPanel));
panel.FindElement(By.Id("middlepanel-showbtn")).Click();
displayedBody = panel.FindElement(By.Id("middlepanel-body"));
Thread.Sleep(5000);
displayedBodyText = displayedBody.Text;
DebanjanB
  • 118,661
  • 30
  • 168
  • 217
Reeves62
  • 59
  • 7
  • I guess that you are calling `FindElement` bevor that element or it's data gets loaded. What does `Click` trigger? Does it load or show the element? – nilsK Jun 30 '20 at 15:27
  • @nilsK it expends the panel to show the text – Reeves62 Jun 30 '20 at 15:31

2 Answers2

1

You have to induce WebDriverWait for the ElementIsVisible() and you can use the following Locator Strategy:

displayedBodyText = new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementIsVisible(By.Id("middlepanel-body"))).Text;
DebanjanB
  • 118,661
  • 30
  • 168
  • 217
1

My guess is that the element is there but the text is filled by some background process so is not immediately present. If you know what the expected text is supposed to be, you can add a WebDriverWait and wait for the expected text.

IWebElement panel = _driver.FindElement(By.Id(currentPanel));
panel.FindElement(By.Id("middlepanel-showbtn")).Click();
new WebDriverWait(_driver, TimeSpan.FromSeconds(30)).Until(d => panel.FindElement(By.Id("middlepanel-body")).Text == "The desired string");
// if you get here, the expected text is present

If you aren't sure what the expected text is going to be, you can swap out the last line for the line below that waits for the text to not be empty.

new WebDriverWait(_driver, TimeSpan.FromSeconds(30)).Until(d => panel.FindElement(By.Id("findMe")).Text != "");
JeffC
  • 18,375
  • 5
  • 25
  • 47