'How to verify Image is visible/exists on front end using <img src> or <a href> tag
Does anyone know how I can verify if an image exists using its <a href>
or <img src>
? I can only verify by its class such as:
it('Verifying vertical product', () => {
cy.get('.stage --vertical').should('be.visible')
})
but I want to know how to verify with img src or href tag. thank you
Full HTML:
<a href="haigclub.diageoplatform.com/en/our-whisky/haig-club-clubman">
<img style="margin: auto; display: block;" class="stage__image"
src="haigclub.diageoplatform.com/user/themes/haig/images/bottle.png">
</a>
Solution 1:[1]
If I understand correctly, you are looking for
cy.get('a[href="..."]')
Similarly
cy.get('img[src="..."]')
where you should add the appropriate text instead of ...
Of course, follow with .should('be.visible')
.
If you want to use a partial match, you can use
cy.get('img[src$="bottle.png"]') // NOTE src$=
Solution 2:[2]
A more explicit test might select href
and .find()
the img, to avoid the problem of returning multiple images.
cy.get('a[href^="haig-club-clubman"]')
.find('img') // find inside previous selector (a[href])
.should('have.attr', 'src')
.and('include', 'bottle.png') // explicit test of src attribute
Solution 3:[3]
If you want to assert the image with the image name you can do something like:
cy.get('img').invoke('attr', 'src').should('include', 'bottle.png')
Solution 4:[4]
Another option is to apply a filter which checks the attribute.
Not optimal here, but useful for more complicated scenarios.
cy.get('img')
.filter('[src^="bottle.png"]')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Jumaane |
Solution 3 | Alapan Das |
Solution 4 | Seke |