How to Find Broken Images with Cypress Testing Library
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:
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:
- Select all image (
img
) elements on the page. - Scroll the image into view and check if it's visible.
- 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.