Reputation: 263
I'm automating a webstore in selenium/Java. If the user hasn't selected the size of a product, a message comes up stating 'this is a required field' next to the size. I'm trying to write an 'if' statement that asserts whether this message is present and the action to take if it is, but I cannot get it to work. It would be something along the lines of this:
WebElement sizeIsRequiredMsg = driver.findElement(By.cssSelector("#advice-required-entry-select_30765)"));
WebElement sizeSmallButton = driver.findElement(By.cssSelector("#product_info_add > div.add-to-cart > div > button"))
if (sizeIsRequiredMsg.equals("This is a required field.")) {
action.moveToElement(sizeSmallButton);
action.click();
action.perform();
}
I've tried a few different variations using the 'this is a required field' message as a web element. Not sure if I need to convert the WebElement for the message to a string somehow? Or include a boolean? Can anyone help?
Upvotes: 1
Views: 1638
Reputation: 5204
Try using getText()
something like this:
EDIT I have added the correct cssSelectors and added try catch
:
WebElement addToCartButton = driver.findElement(By.cssSelector("#product_info_add button"));
action.moveToElement(addToCartButton);
action.click();
action.perform();
try {
WebElement sizeIsRequiredMsg = driver.findElement(By.cssSelector(".validation-advice"));
WebElement sizeSmallButton = driver.findElement(By.cssSelector(".swatches-container .swatch-span:nth-child(2)"))
if (sizeIsRequiredMsg.getText() == "This is a required field.") {
action.moveToElement(sizeSmallButton);
action.click();
action.perform();
}
} catch (Exception e) {
System.out.println(e);
logger.log(Level.SEVERE, "Exception Occured:", e);
};
Hope this helps you!
Upvotes: 2