简体   繁体   中英

How to handle Selenium findElements while elements is not present in html tag

In UI if entered text is invalid then error element/tag displaying on UI as well as in HTML code

<div _ngcasde-ltw-c3="" class="error"> Organization only contain alpha chars or special chars -,. </div>

if enter a valid text then no error element/tag displaying on UI as well as in HTML code,

No error in HTML tag

So while writing selenium webDriver code, I have added below code and it works while error in HTML code (invalid text scenario) but while no error tag in HTML code (valid text scenario), my execution stuck in below code line (elements OR count OR result) and not proceed further. it remain showing execution running in that line for unlimited time

WebElement xyz = driver.findElement(By.className("modal-body"));

List<WebElement> elements = xyz.findElements(By.xpath("//div[@class='error']"));
OR
int count = xyz.findElements(By.xpath("//div[@class='error']")).size();
OR
boolean result = xyz.findElement(By.xpath("//div[@class='error']")).isDisplayed();

So please let me know how to handle this and proceed further, if element not present then it should return size 0 or result as false

Based on this output I will use if clause to print message, error if size is not zero and success if size is 0

Declare your error element using FindBy annotation and use it only when the error gets generated on the page.

@FindBy(id = "foobar") WebElement foobar;

Example:

@FindBy(id = "error_css") WebElement errorElement;

public void verifyError(){
    // Click on Save button without filling out mandatory fields on the form
    save.click();
    // Now validate error as it will be generate on the HTML 
    errorElement.gettext();   
}

Happy Testing:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM