Advertisement |
You might have faced scenarios where you had to verify the images loaded completely on the page or loaded broken. Doing it manually could be one way but it may become difficult if you have to actually verify the images is loaded using Automation, but Selenium has the solution for this problem.
Let's see how we can validate broken and loaded images :
So what you can do is use JavaScriptExcecutor interface which has a method executeScript(). You can check if the image is getting displayed or not by calling the executeScript method of the JavaScriptExcecutor Interface.
public void verifyImageLoaded(String imageSrc){ WebElement image = driver.findElement(By.xpath("//img[@src='"+imageSrc+"']")); Object checkResult = ((JavascriptExecutor) driver).executeScript( "return arguments[0].complete && "+ "typeof arguments[0].naturalWidth != \"undefined\" && "+ "arguments[0].naturalWidth > 0", image); boolean loaded = false; loaded = (Boolean) checkResult; Assert.assertTrue("Image was not rendered properly", loaded); }
This method validates if the image with the given source has been loaded completely or not. checkResult will be returned as an object so to get the Boolean value you need to typecast checkResult to fetch the boolean value.
To Validate Broken Image: To check if the method works fine with broken images, just try to send the wrong URL for the image source and the method will fail at the Assert statement with the false value for the 'loaded' variable. The broken image looks something like below image :
Try the code and write to me if you face some issue.
0 comments: