Home > Back-end >  How to return the number of occurences of an element on a webpage
How to return the number of occurences of an element on a webpage

Time:03-17

On a webpage there are a number of images that appear .img I was wondering how to get the number of images that appear and return that as a variable to use for other tests

I had this written, but this does not produce anything, just an empty variable

cy.get('.img').then(($img) => {
   cy.wrap($img).its('length').then((val)=>{
      return val;
   });
})

How can I return the number of occurences (without using any assertions like should have length)? Other solutions I tried produced sync/async errors

CodePudding user response:

You will want to do something like this.

// maybe have this in beforeEach()
cy.get('.img').its('length').as('numImgs')


// later in a test
cy.get('@numImgs') // to get number of occurrences 

CodePudding user response:

If you want to use the length value for other tests in the same test suite or in other test suites, you can save the value in Cypress.env and then use it wherever you want like this:

cy.get('.img')
  .its('length')
  .then((len) => {
    Cypress.env('imgLen', len)
  })

Then In your test, You can use it like this:

Cypress.env('imgLen')
cy.log(Cypress.env('imgLen')) //logs img length
cy.get('selector').should('have.length', Cypress.env('imgLen')) //Asserts the length
  • Related