Waiting for one of two elements to be displayed

Viewed 39

So this app I'm automating at work has scenarios where the same button is used to navigate to different screens based on various scenarios that could happen. The app also has various timing issues that usually pop up during automation.

Previously I've used WebDriverWait for handling these timing issues by waiting for an element to be displayed / not displayed but now I find myself having to wait for element1 or element2 to be displayed.

I found a way of doing it with an XPath where I use the pipe character to essentially combine 2 xpaths:

var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(maxTimeoutInSeconds))            
.Until(ExpectedConditions.ElementIsVisible(By.XPath("//select[@id='dropdown']|//input[@id='firstname']"))); 

Is there a way to do this with something other than XPath, like By.Id or By.LinkText?

Is there a more recommended approach for handling a wait for element1 or element2?

UPDATE
I threw together a method based on a comment below and it's throwing a NoSuchElementException whenever the first Displayed condition is false and never actually making it to the 2nd.

public void WaitForStuff(By element1, By element2)
{
    try
    {
        new WebDriverWait(driver, TimeSpan.FromSeconds(30)).Until(driver => driver.FindElement(element1).Displayed || driver.FindElement(element2).Displayed);
    }
    catch (Exception e)
    {
         throw;
    }
}
1 Answers

I highly reccommend using this

wait.Until(driver => driver.FindElement(By.XPath("xpath")).Displayed
                  || driver.FindElement(By.XPath("xpath")).Displayed);

It stops at this line until one of the two elements is displayed. It's an ole' reliable for me. I use it countless times and it's rarely let me down.

Related