1

I have multiple divs with multiple imgs under them. I'd like to get the div with the correct img src. How can I do this? I tried this and it didn't work. It just compared the src with the first div and failed.

cy.get('.card').find('.info-section > .logo').should('have.attr', 'src', '/assets/icons/fruit.svg')
by3by3byt3
  • 67
  • 6

2 Answers2

1

Reverse the search order - target the child element with that specific attribute, then traverse to the card parent

cy.get('[src="/assets/icons/fruit.svg"]')
  .parent('.card')
Fody
  • 23,754
  • 3
  • 20
  • 37
0

It would greatly help your situation if you provided the DOM to see the multiple divs and imgs.

I'll be using the example DOM below.

<div class="card">
    <div class="info-section">
        <img src="/assets/icons/vegetable.svg" />
        <div class="logo">
            <img src="/assets/icons/fruit.svg" />
        </div>
    </div>
</div>

<div class="card">
    <div class="info-section">
        <img src="/assets/icons/vegetable.svg" />
        <div class="logo">
            <img src="/assets/icons/fruit.svg" />
        </div>
    </div>
</div>

To get the <img src="/assets/icons/fruit.svg" /> and test it has src, you will do the following:

cy.get('div.logo') // get div with class logo
  .find('img') // find img children
  .should('have.length', 1) // should only return 1 element
  .should('have.attr', 'src', '/assets/icons/fruit.svg') // should have src attr
jjhelguero
  • 2,281
  • 5
  • 13
  • `.children('img')` should be `.find('img')` - your comment is correct! See the [example](https://docs.cypress.io/api/commands/children#No-Args), children does not mean descendants. – Fody Jan 26 '22 at 05:35
  • Ops, hehe. Thanks for that good catch! For my specific example `.children()` would work but probably better to use `.find()`. – jjhelguero Jan 26 '22 at 05:39