skies.dev

How to Find Broken Images with Cypress Testing Library

2 min read

Have you ever been to a site where an image doesn't load and you're stuck reading the alt tag?

It looks something like this:

Example of what it looks like in the browser when an image doesn't load.
Example of what it looks like in the browser when an image doesn't load.

Surely, you don't want this to be the case on your site.

Unfortunately, if you have a lot of pages on your site, it will be difficult to manage knowing when the src URL of an image breaks.

Wouldn't it be great if there was a way to automatically determine if an image isn't loading?

Turns out, we can! With the help of Cypress Testing Library, we can automate scanning our website for broken images. Here's how we'll do it:

  1. Select all image (img) elements on the page.
  2. Scroll the image into view and check if it's visible.
  3. Ensure the natural width and height is greater than 0.

We use cy.scrollIntoView() for each image in case the image is hidden inside of an overflow area.

If either of steps 2 or 3 fail, then you probably have a broken image.

// 1. Select all image (`img`) elements on the page.
cy.get('img').each(($img) => {
  // 2. Scroll the image into view and check if it's visible.
  cy.wrap($img).scrollIntoView().should('be.visible');

  // 3. Ensure the natural width and height is greater than 0.
  expect($img[0].naturalWidth).to.be.greaterThan(0);
  expect($img[0].naturalHeight).to.be.greaterThan(0);
});

With this you can feel at ease knowing the images you show to your users work.

Hey, you! 🫵

Did you know I created a YouTube channel? I'll be putting out a lot of new content on web development and software engineering so make sure to subscribe.

(clap if you liked the article)

You might also like