Reputation: 1142
Given the Page Object Model design pattern in Selenium, I need to check if the WebElement is present/enabled/clickable on the page before performing an action on it.
The base 'Page' class:
public class Page
{
public Page()
{
PageFactory.InitElements(SeleniumTests.driver, this);
}
}
An inherited class:
class Page_Certificate_ChooseOperator : Page
{
[FindsBy(How = How.Id, Using = "SearchOperatorName")]
public IWebElement txtName { get; set; }
[FindsBy(How = How.Id, Using = "SearchOperatorEstablishmentNumber")]
public IWebElement txtEstablishmentNumber { get; set; }
[FindsBy(How = How.Id, Using = "searchButton")]
public IWebElement btnSearch { get; set; }
public void SelectOperator(String name, String establishmentNumber)
{
this.txtName.SetInputField(name);
this.txtEstablishmentNumber.SetInputField(establishmentNumber);
this.btnSearch.SafeClick();
}
}
Finally the class for the extension methods:
public static class SeleniumExtensionMethod
{
public static void SetInputField(this IWebElement webElement, String value)
{
webElement.Clear();
webElement.SendKeys(value);
}
public static void SafeClick(this IWebElement webElement, int timeout_in_seconds)
{
//This is the difficult part. I need to check if the webElement is visible, but I don't want to write "low-level" code and specify the ID and selector. Is there a way I can find out how the webElement was created by this class and say something like "webElement.How" to find "How.ID" or "webElement.Using" to find "btnSearch"? I need to use something like the below code using the PageObject
// WebDriverWait wait = new WebDriverWait(SeleniumTests.driver, TimeSpan.FromSeconds(10));
// IWebElement dynamicElement = wait.Until<IWebElement>(driver => driver.FindElement(By.Id("btnSearch")));
// dynamicElement.Click();
//Now, I just use this, but it crashes on NoSuchElementFound since it goes too fast. I don't want to use ImplicitWait.
btnSearch.Click();
}
}
The challenge I'm facing is that I need an ExplicitWaity before clicking on the button btnSearch
as it throws a a NoSuchElementFoundException. Since I use the [FindsBy] attribute, I figure there should be some way to check how the webElement was found/created? How can I do this? Or how I can have neat code and use ExplicitWait on a Page Object?
Upvotes: 1
Views: 2089
Reputation: 42528
To wait for an element to be present/enabled/clickable, you can use a waiter with the ElementToBeClickable
condition:
[FindsBy(How = How.Id, Using = "searchButton")]
public IWebElement btnSearch { get; set; }
public void SelectOperator(String name, String establishmentNumber)
{
this.txtName.SetInputField(name);
this.txtEstablishmentNumber.SetInputField(establishmentNumber);
new WebDriverWait(SeleniumTests.driver, TimeSpan.FromSeconds(10))
.Until(ExpectedConditions.ElementToBeClickable(this.btnSearch))
.Click();
}
Upvotes: 1