skies.dev

How to Find Broken Images with Cypress Testing Library

2 min read

Broken images are easy to miss in local development and painful in production. Users see empty space, broken icons, or just the alt text, and by the time someone reports it the page has already looked broken for a while.

You can catch most of those failures with a simple Cypress check:

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.

The pattern is straightforward:

  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.

cy.scrollIntoView() helps with images inside lazy-loaded sections, carousels, or any container that hides content behind overflow.

If either step fails, the image is probably broken or never finished loading.

// Select every image on the page.
cy.get('img').each(($img) => {
  // Make sure Cypress can actually see the element.
  cy.wrap($img).scrollIntoView().should('be.visible');

  // A loaded image should always have real dimensions.
  expect($img[0].naturalWidth).to.be.greaterThan(0);
  expect($img[0].naturalHeight).to.be.greaterThan(0);
});

If you want to reduce false positives, scope the query to the sections that matter most, such as article content, product pages, or marketing pages. That keeps the test fast and focused while still catching the broken images users are most likely to notice.

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