๐ WebDriverIO Image Validation: Automate Broken Image Detection Effortlessly
Introduction
In the fast-paced world of web development and testing, ensuring a seamless user experience is paramount. One of the often overlooked yet critical aspects is the detection of broken images on a website. In this article, we will delve into the realm of automation testing and explore how the WebDriverIO tool can be harnessed to find and address broken images effectively. This guide is tailored for tech-savvy individuals keen on optimizing their testing processes.
The Need for Automated Image Validation
As websites become increasingly complex with dynamic content and numerous dependencies, manually validating images becomes a daunting task. Automated image validation emerges as a saviour, streamlining the process and ensuring a meticulous check for broken images. WebDriverIO, a robust automation tool, steps into the spotlight, offering a powerful solution for this challenge.
Importance of image validation in web testing
When a link or image fails to display as intended, it is known as a broken image. If a user clicks on the broken image, they will be taken to a page where the image is no longer available, resulting in a 404 error. This error message indicates that there is an issue with the image URL, and the image is not able to load properly due to various reasons.
Shown below is an example of broken images: https://the-internet.herokuapp.com/broken_images
It is important to prioritize fixing broken images on websites as much as fixing broken links from an end-user experience and retention point of view. Selenium WebDriver is a useful tool for detecting broken images on websites. The method for locating broken images may differ depending on how images are retrieved from the server.
What are the Major reasons for Broken images on a website?
Ever encountered a webpage riddled with blank squares and broken image icons? Those, my friend, are the dreaded broken images, and they can spell trouble for your website. Let's delve into the top culprits behind these missing visuals and understand why addressing them is crucial.
The Usual Suspects:
Format Mismatch: Imagine uploading a picture as a .jpg but coding it as a .png. This identity crisis confuses the browser, leaving you with a blank stare instead of the intended image. Ensure format consistency between uploads and code references.
URL Errors: The browser relies on the image's address embedded in the code to find it. Typos, wrong filenames, or non-existent paths lead to a classic 404 error, leaving the image slot empty. Double-check those URLs!
Deleted Image file: The code might point to an image that either has a misspelling or has vanished from the server entirely. Regular audits can help identify and fix these "ghost" references.
Site relocation: Shifting your site to a new server? Don't forget to pack all your visual assets! Incomplete transfers or forgotten files can result in broken images on the new home.
Redirections 301: Website revamps often involve redirects. Remember to update references not just for pages, but also for the images nestled within them. A broken redirect leaves the image lost in the digital wilderness.
Server Unavailability: Sometimes, servers take a nap or get overloaded. When that happens, images might fail to load, leaving empty spaces in their wake. Monitor server health to avoid these temporary glitches.
Why Fix Broken Images?
Just like broken links, broken images are bad news for websites. Here's why you should care:
1. Frustrated Visitors: Nobody likes seeing missing pictures. They disrupt the flow of information and create a poor user experience, which can drive people away from your website.
2. SEO Woes: Images are powerful for SEO, but broken ones can hurt your ranking. Missing alt tags and internal image errors are red flags for search engines, so fix them to stay on top.
Remember, keeping your website free of broken images is like keeping your house tidy. It makes a good impression and ensures everything runs smoothly!
How to Find Broken Images Using WebDriverIO?
How to find Broken Images using HTTP API Response?
How to find Broken Images using NaturalWidth Attribute variation 1?
How to find Broken Images using NaturalWidth Attribute Variation 2?
How to find Broken Images using HTTP API Response?
The provided code is a TypeScript function for checking broken images on a web page based on the HTTP response code of the image URLs. Here's a breakdown of the code:
/**
* Asynchronously checks for broken images in a given WebdriverIO ElementArray using the HTTP response code.
* @param {WebdriverIO.ElementArray} webElement - WebdriverIO ElementArray containing image elements to be checked.
*/
async function checkBrokenImagesUsingResponseCode(webElement: WebdriverIO.ElementArray) {
try {
// Get the images
const images = await webElement;
// Iterate over each image and check the HTTP response code
for (const image of images) {
const src = await image.getAttribute('src');
console.log("Src - " + src);
// Execute JavaScript to fetch the image URL and get the response status
const response: number = await browser.execute(async (url: string) => {
const response = await fetch(url);
return response.status;
}, src);
console.log("Fetched URL - " + response);
// Check for broken images (status other than 200 OK)
if (response !== 200) {
console.error(`Broken image found: ${src}`);
}
}
} catch (error) {
console.error(`Error occurred: ${error}`);
throw error;
}
}
Explanation:
The function
checkBrokenImagesUsingResponseCode
is an asynchronous function that takes a WebdriverIO ElementArray (webElement
) as its parameter. This ElementArray should contain image elements that need to be checked for broken images.The function iterates over each image in the ElementArray, extracts its source URL using
getAttribute('src')
, and logs it.It then uses the
browser.execute
method to execute asynchronous JavaScript code in the browser context. The JavaScript code uses the Fetch API to fetch the image URL and returns the HTTP response status code.The response status is logged, and if it is not equal to 200 (OK), the function logs an error message indicating that a broken image was found.
How to find Broken Images using naturalWidth
Attribute variation 1?
The provided code is a TypeScript function for checking broken images on a web page using the WebDriverIO library and the naturalWidth
attribute of the HTML Image
element. Here's a breakdown of the code:
/**
* Asynchronously checks for broken images in a given WebdriverIO ElementArray using the naturalWidth attribute.
* @param {WebdriverIO.ElementArray} webElement - WebdriverIO ElementArray containing image elements to be checked.
*/
async function checkBrokenImagesUsingNaturalWidthAttributeV1(webElement: WebdriverIO.ElementArray) {
try {
// Find all image elements on the page
const images = await webElement;
// Iterate through each image and check its naturalWidth
for (const image of images) {
const imageUrl = await image.getAttribute('src');
// Use JavaScript executor to check naturalWidth
const naturalWidth = await browser.executeAsync(async function (imageUrl, done) {
const img = new Image();
img.onload = function () {
done(img.naturalWidth);
};
img.onerror = function () {
done(0); // Set width to 0 if the image fails to load
};
img.src = imageUrl;
}, imageUrl);
// Check if the image has a natural width of 0 (indicating a broken image)
if (naturalWidth === 0) {
await console.log(`${imageUrl} image is broken with width ${naturalWidth}`);
}
// Uncomment the line below if using assertion library like Chai
// assert.strictEqual(naturalWidth, 0, `Image ${imageUrl} is broken`);
}
} catch (error) {
console.error(`Error occurred: ${error}`);
throw error;
}
}
Explanation:
The function
checkBrokenImagesUsingNaturalWidthAttributeV1
takes a WebdriverIO ElementArray (webElement
) as its parameter. This ElementArray should contain image elements that need to be checked for broken images.It iterates through each image in the ElementArray and extracts its source URL using
getAttribute('src')
.Inside the loop, it uses
browser.executeAsync
to execute asynchronous JavaScript code in the browser context. This code creates anImage
object, sets itssrc
attribute to the image URL, and checks thenaturalWidth
property when the image loads. If the image fails to load, it sets the width to 0.If the
naturalWidth
of the image is 0, it logs a message indicating that the image is broken.
How to find Broken Images using naturalWidth
Attribute variation 2?
The provided code is a TypeScript function for checking broken images on a web page using the WebDriverIO library and the naturalWidth
attribute of the HTML Image
element. Here's a breakdown of the code:
/**
* Asynchronously checks for broken images in a given WebdriverIO ElementArray using the naturalWidth attribute.
* @param {WebdriverIO.ElementArray} webElement - WebdriverIO ElementArray containing image elements to be checked.
*/
async function checkBrokenImagesUsingNaturalWidthAttributeV2(webElement: WebdriverIO.ElementArray) {
try {
// Get the images and their source URLs
const images = await webElement;
const imageUrls = await Promise.all(await images.map(async image => {
return image.getAttribute('src');
}));
// Execute JavaScript to check naturalWidth for each image URL
const naturalWidths = await Promise.all(imageUrls.map(async imageUrl => {
return browser.execute(function (imageUrl) {
const img = new Image();
img.src = imageUrl;
return img.naturalWidth;
}, imageUrl);
}));
// Check for broken images
naturalWidths.forEach((naturalWidth, index) => {
if (naturalWidth === 0) {
console.log(`Broken image found: ${imageUrls[index]}`);
}
});
} catch (error) {
console.error(`Error occurred: ${error}`);
throw error;
}
}
Explanation:
The function
checkBrokenImagesUsingNaturalWidthAttributeV2
takes a WebdriverIO ElementArray (webElement
) as its parameter. This ElementArray should contain image elements that need to be checked for broken images.The function first extracts the source URLs of all the images in the ElementArray using
getAttribute('src')
and stores them in theimageUrls
array.It then uses the
browser.execute
method to execute JavaScript code in the browser context. The JavaScript code creates anImage
object, sets itssrc
attribute to the image URL, and retrieves thenaturalWidth
property. The results are stored in thenaturalWidths
array.Finally, the function iterates over the
naturalWidths
array, and for any image with anaturalWidth
of 0, it logs a message indicating that a broken image was found.
Reports
Follow Github Repository
For updated code:-
Summary
Embark on a journey to master WebDriverIO Image Validation and transform your approach to image testing. In this comprehensive guide, we explore how to leverage WebDriverIO for efficient and automated detection of broken images, ensuring a seamless user experience. From understanding common image issues to implementing practical solutions, this article covers everything you need to know about WebDriverIO Image Validation. Discover how to streamline your testing process and maintain the visual integrity of your website with effective automation techniques.
Subscribe to my newsletter
Read articles from Hardik Chotaliya directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Hardik Chotaliya
Hardik Chotaliya
๐ฉโ๐ป Automation QA Engineer || SDET ||โ๐ผ Tech Blogger || WebdriverIO, JavaScript, TypeScript || based in ๐ฎ๐ณ || ๐ค Life-long learner ||Love โ & ๐