Search code examples
javalistseleniumselenium-webdriverpageobjects

Why list is required just to cancel single pop up in selenium webdriver?


In Page Object factory:

By popup=By.xpath("//button[test()='NO THANKS']");

public List<WebElement> getPopUpSize(){
return driver.findElements(popup);
}

public WebElement getPopUp(){
return driver.findElement(popup);
}

Calling above methods into Testcase:

LandingPage l = new LandingPage(driver);
if(l.getPopUpSize().size()>0)
{
l.getPopUp().click();
}

I didn't understand why do we have to create a list just to cancel single pop up?


Solution

  • No, you do not need findElements for a single web element. Use findElement instead or Explicit waits as illustrated below:

    1. Using ExplicitWaits

    Code:

    public WebElement getPopUpWebElement(){
        return driver.findElement(popup);
    }
    

    and in test method:

        try {
            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
            wait.until(ExpectedConditions.elementToBeClickable(getPopUpWebElement())).click();
        }
        catch(Exception e){
            System.out.println("Could not click on pop up");
            e.printStackTrace();
        }