5

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?

urig
  • 16,016
  • 26
  • 115
  • 184
  • 1
    Did you check this already? https://docs.cypress.io/guides/core-concepts/conditional-testing.html#Definition or this: https://stackoverflow.com/questions/47773525/how-to-check-for-an-element-that-may-not-exist-using-cypress – briosheje Mar 25 '19 at 10:39
  • Thanks. This might do it for me: https://docs.cypress.io/guides/core-concepts/conditional-testing.html#Element-existence . Keeping in mind the jquery API does not have cypress' "wait loop" – urig Mar 25 '19 at 10:47

2 Answers2

3

You can use the length assertion

cypress.get('.some-class').should('not.have.length', 0);
Yep_It's_Me
  • 4,494
  • 4
  • 43
  • 66
  • I don't think this answer solves the question, but did help me to assert that a certain number of DOM elements exist, like `cy.get('[data-cy=foo]').should('have.length', 2);`. I should also mention that you should be using `data-cy`, not class selectors. – Erebus Apr 24 '20 at 16:09
1

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
        }
      }
    })
  })
KunduK
  • 32,888
  • 5
  • 17
  • 41