There is nothing more embarrassing than a broken image link right there in the middle of the page.
Can we catch broken images using Cypress tests?
🎁 The source code for this blog post can be found in my recipe "Image Has Loaded" at glebbahmutov.com/cypress-examples.
📺 Watch this example in the video Check Broken Images On The Page.
Check a single image
Imagine a single <img>
element. It loads the image using its src
attribute. The source could be a link URL, or a data:...
encoded image. Even if the URL is valid, the image itself could be corrupted and the browser might fail to decode it. Thus we want to check if the image loads, rather than simply checking the URL. A good way to check is to confirm the naturalWidth
or naturalHeight
of the img
element. For successfully loaded and decoded images it should be positive.
1 | <img |
1 | cy.get('#loads') |
If the src
URL points at a non-existent image, the test catches it.
📺 You can find this example explained in the video Check If An Image Loads.
Multiple images
Now let's check all images on the page. Rather than failing a test immediately, we will collect all broken image information before reporting it all at once. This allows us to judge how broken the page is and maybe even debug it faster. Imagine multiple images on the page. Some elements load the image from a remote URL, others use data:...
encoding, or even an SVG element.
1 | <img |
Let's check all images at once.
1 | const brokenImages = [] |
By reporting id
and alt
attribute we can point the team to the right direction. We could also use cyclope plugin to save the entire page as static HTML snapshot to debug the markup.