0

I'm new to selenium and JS SweetAlert2. I want to check if the SweetAlert2 is displayed or not. I was able to do so using the isDisplayed() function. Nonetheless, once the SweetAlert2 is closed, the isDisplayed() function can't locate it anymore. Thus, I get the following error: No such element: Unable to locate element: ....

Below is my code:

boolean actual_SwtAlert = driver.findElement(By.xpath("Rel Xpath Location")).isDisplayed();
boolean expected_SwtAlert = false;

if (actual_SwtAlert == expected_SwtAlert) {
    System.out.println("Successfully closed SweetAlert2!");
} else {
    System.out.println("Failed to close SweetAlert2!");
}
Assert.assertEquals(actual_SwtAlert, expected_SwtAlert);

How can I do this?

F. Müller
  • 3,969
  • 8
  • 38
  • 49

2 Answers2

0

Try with this solution:

public boolean isDisplayed(WebElement element) {
            try {
                return element.isDisplayed();
            } catch (NoSuchElementException e) {
                return false;
            }
        }

boolean actual_SwtAlert = isDisplayed(driver.findElement(By.xpath("Rel Xpath Location")));
boolean expected_SwtAlert = false;

if(actual_SwtAlert == expected_SwtAlert) {
    System.out.println("Successfully closed SweetAlert2!");
}else {
    System.out.println("Failed to close SweetAlert2!");

}
Assert.assertEquals(actual_SwtAlert, expected_SwtAlert);

But I can not understand the use case of the last row (Assertion)

The better solution I think is:

public boolean isDisplayed(WebElement element) {
                try {
                    return element.isDisplayed();
                } catch (NoSuchElementException e) {
                    return false;
                }
            }

boolean isAlertDisplayed = isDisplayed(driver.findElement(By.xpath("Rel Xpath Location")));

    if(isAlertDisplayed) {
       System.out.println("Failed to close SweetAlert2!");
        
    }else {
       System.out.println("Successfully closed SweetAlert2!");

    }
Norayr Sargsyan
  • 1,737
  • 1
  • 12
  • 26
0

Use Try/catch block to catch that exception.And use webdriver wait as best practice

   try{   
        WebDriverWait wait = new WebDriverWait(driver,30);
        WebElement popup=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("XPATH")));
                          
        if(popup.isDisplayed()) {
            System.out.println("Successfully closed SweetAlert2!");
        }
        //Assert.assertEquals(actual_SwtAlert, expected_SwtAlert);
}
Catch(Execption e){
 System.out.println("Failed to close SweetAlert2!");
}
Amruta
  • 1,128
  • 1
  • 9
  • 19