urig
urig

Reputation: 16831

In cypress.io, how can I count a number of elements without failing the test if there are none?

Using cypress.io I can get a list of HTML elements matching a given CSS selector like so:

cypress.get(".some-class")

If no elements having the class 'some-class' are found on the page, the test fails. This is by design.

I would like to try to get a list of HTML elements as above, but not to fail the test if the number of elements is 0.

How can I achieve this using cypress.io?

Upvotes: 5

Views: 11079

Answers (2)

Yep_It's_Me
Yep_It's_Me

Reputation: 4801

You can use the length assertion

cypress.get('.some-class').should('not.have.length', 0);

Upvotes: 3

KunduK
KunduK

Reputation: 33384

You can do it following way.This will keep your test alive.

describe('test check element', function () {
    it('testSelector reload', function () {
      cy.visit('https://docs.cypress.io/api/utilities/$.html#Usage')
      let found = false
      let count=0
      while (!found) {

        const nonExistent = Cypress.$('.fake-selector')

        if (!nonExistent.length) {
          cy.reload()
          found = false
          count=count+1
          cy.wait(1000)
          if(count==5)
          {
            found = true
            cy.log('Element not found after 5 seconds..Exit from loop!!!')
          }
        } else {
          found = true
        }
      }
    })
  })

Upvotes: 1

Related Questions