Search code examples
javaseleniumautomation

Selenium Automation - How to click on particular button periodically until getting another element's updated text value?


In my webpage, I have a refresh button and one Text Field, when i landed to that page, Initially that Text Field value would be processing (In backend there is a functionality which is processing, Inorder to inform the user, textfield value is processing in UI), and after functionality is done, that Text Field would be completed

Now coming to the question, We will get to know the updated value of Text Field only when we click on the refresh button,

Is there a way to make a WebElement to be waited until that Text field has value as completed? We also need to click on that particular refresh button periodically to check that text field value became completed or not

I've found a method called textToBePresentInElement in ExpectedConditions, But using this, we cannot refresh button periodically, Any other solution selenium webdriver is providing?


Solution

  • It's possible to implement a custom Expected condition:

    import org.openqa.selenium.support.ui.ExpectedCondition
    
    public static ExpectedCondition<Boolean> textToBePresentForElementWithRefreshByClick(By originalElement, Strint expectedText, By refreshElement) {
        return new ExpectedCondition<Boolean>() {
            private boolean hasText = false;
            private String currentText = "";
    
            @Override
            public Boolean apply(WebDriver driver) {
                currentText = driver.findElement(originalElement).getText();
                hasText = currentText == expectedText;
                if(!hasText) {
                    driver.findElement(refreshElement).click();
                    // Optionally some sleep might be added here, like Thread.sleep(1000);
                }
                return hasText;
            }
    
            @Override
            public String toString() {
                return String.format("element \"%s\" should have text \"%s\", found text: \"%s\"", originalElement.toString(), expectedText, currentText);
            }
        };
    }
    

    Usage:

    By originalElement = ...;
    By refreshElement = ...;
    
    new WebDriverWait(driver, Duration.ofSeconds(10)).until(
        textToBePresentForElementWithRefreshByClick(originalElement, "completed", refreshElement)
    )