7

How do I get an element in Cypress without it asserting that it is present?

cy.get('.something')

Sometimes my element might not be there and I don't want it to fail the test.

Is there a different command I should be using?

Sebastian Patten
  • 7,157
  • 4
  • 45
  • 51
  • 2
    Possible duplicate of [Cypress: Can I prevent Cypress cy.get from failing if no elements are found?](https://stackoverflow.com/questions/54150776/cypress-can-i-prevent-cypress-cy-get-from-failing-if-no-elements-are-found) – Richard Matsen Oct 04 '19 at 00:15

2 Answers2

8

You can use cy.$$('selector') to synchronously query for an element (jquery).

If you want this to happen after a cypress command, you'll need a .then:

cy.visit('/')
cy.get('element-one').then(() => {
  const $el2 = cy.$$('element-two')
  if ($el2.length) {
    // do this
  } else {
    // do that
  }
})
kuceb
  • 16,573
  • 7
  • 42
  • 56
1

You might want to check this section of the docs in Cypress https://docs.cypress.io/guides/core-concepts/conditional-testing.html#Element-existence

Vividh S V
  • 131
  • 1
  • 7