How to test for a broken image in Cypress

Viewed 44

I want to test for broken images on the page.

If I inspect the DOM for the broken image I see

<img src="https://www.example.com/images/a123.jpg" alt="a123">
  #shadow-root (user-agent)
  <span id="alttext-container">
    <img id="alttext-image" width="16" height="16" align="left" style="margin: 0px; 
      display: inline; float: left;">
    <span id="alttext">a123</span>
  </span>

But if I try to access the alttext in the test it fails.

cy.get('img[src="https://www.example.com/images/a123.jpg"]')
  .shadow()
  .find('span[id="alttext"]')

How do I verify the alt text that shows on the screen.

1 Answers

Unfortunately the #shadow-root (user-agent) child element can't be accessed from javascript, so it also can't be queried with Cypress commands.

The best you can do to verify the image isn't broken is to check it's naturalWidth property

cy.get('img[src="https://www.example.com/images/a123.jpg"]')
  .should('be.visible')
  .and($img => expect($img[0].naturalWidth).to.be.gt(0))
Related