Crack the Code: Finding Broken Images Made Effortless with WebDriverIO Automation
Published: 2024-02-18 06:08:17

## 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 savior, 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](https://the-internet.herokuapp.com/broken_images)

![How To Find Broken Images Using the WebDriverIO Automation
](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bxepcxt3jx3ht8dxn7nm.png)

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:

```typescript
/**
 * 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:***

1. 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.
    
2. The function iterates over each image in the ElementArray, extracts its source URL using `getAttribute('src')`, and logs it.
    
3. 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.
    
4. 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:

```typescript
/**
 * 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:***

1. 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.
    
2. It iterates through each image in the ElementArray and extracts its source URL using `getAttribute('src')`.
    
3. Inside the loop, it uses `browser.executeAsync` to execute asynchronous JavaScript code in the browser context. This code creates an `Image` object, sets its `src` attribute to the image URL, and checks the `naturalWidth` property when the image loads. If the image fails to load, it sets the width to 0.
    
4. 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:

```typescript
/**
 * 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:***

1. 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.
    
2. The function first extracts the source URLs of all the images in the ElementArray using `getAttribute('src')` and stores them in the `imageUrls` array.
    
3. It then uses the `browser.execute` method to execute JavaScript code in the browser context. The JavaScript code creates an `Image` object, sets its `src` attribute to the image URL, and retrieves the `naturalWidth` property. The results are stored in the `naturalWidths` array.
    
4. Finally, the function iterates over the `naturalWidths` array, and for any image with a `naturalWidth` of 0, it logs a message indicating that a broken image was found.
    

---

## Reports:


![Automation Reports](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bv6asiaj82v06znblwum.png)



---

## Follow Github Repository

*For updated code:-*

[GitHub Repo](https://github.com/hardikchotaliya)

---

## Summary

Embark on a transformative journey as we unveil the secrets to effortlessly broken image detection in web applications using the formidable WebDriverIO automation tool. In our guide, "Crack the Code: Finding Broken Images Made Effortless with WebDriverIO Automation," we delve into the dynamic realm of automated testing, catering specifically to tech enthusiasts and professionals eager to optimize their testing processes.

Setting the stage, we navigate through the intricate process of setting up WebDriverIO, establishing a robust foundation for comprehensive testing environments. The article delves into the complexities of image validation, highlighting the challenges posed by dynamically loading images and the indispensable role WebDriverIO plays in overcoming these hurdles.

The core of our exploration lies in detecting broken images with WebDriverIO, where we leverage its powerful commands to script custom solutions for efficient identification. Visual regression testing takes center stage, ensuring a meticulous check for any discrepancies in image rendering. Packed with practical examples and code snippets, this section empowers readers to implement these techniques seamlessly.

Navigating through potential image-related errors is a crucial aspect of any automated testing process. Our guide equips readers with effective debugging techniques, emphasizing the importance of logging and reporting broken image errors to streamline the troubleshooting process.

As we progress, the integration of image validation into continuous integration workflows becomes a focal point, ensuring a harmonious union between automated testing and development pipelines. The article concludes with a spotlight on best practices, offering valuable insights into optimizing image validation scripts and fostering collaboration with development teams.

Intrigued readers are invited to "Crack the Code" and revolutionize their testing game with WebDriverIO's automation brilliance. The guide encapsulates not just a technical exploration but a thrilling odyssey into the future of web development testing, where finding and addressing broken images becomes an effortless feat. Unlock the power, precision, and ease of WebDriverIO automation for a visually impeccable web experience.

---