Home > database >  How to verify Image is visible/exists on front end using <img src> or <a href> tag
How to verify Image is visible/exists on front end using <img src> or <a href> tag

Time:03-03

simple question but still new to cypress, 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;"  
    src="haigclub.diageoplatform.com/user/themes/haig/images/bottle.png"> 
</a>

enter image description here

CodePudding user response:

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$= 

CodePudding user response:

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')

CodePudding user response:

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

CodePudding user response:

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"]')
  • Related