Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

142
Vistas
How to not break Cypress tests if element you'r looking for is not exist

I have the div with classname 'okrSelectorSelect__value-container' in DOM.

<div class="okrSelectorSelect__value-container"><div>

This div is optional. I want to click on it and do some additional tests with block that appears after that IF IT EXIST. I'm trying this.

cy.get('.okrSelectorSelect__value-container').then(($higherObjectivePick) => {
 if ($higherObjectivePick.length > 0) {
  $higherObjectivePick.click();
 }
});

But got this when block is not on the page

enter image description here

Here is my solution, but looks like there is much more beautiful ways to do that.

 cy.get('body').then($body => {
    if ($body.find('.okrSelectorSelect__value-container').length > 0) { 
      cy.get('.okrSelectorSelect__value-container').click();
      cy.get('.okrSelectorSelect__option').eq(higherOrderObjectiveNumber).click();
    }
  }); 
about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

You could use jquery operators to check the existence of an element and wrap that function as below, adding to your support.js file:

Cypress.Commands.add("checkIfClassExists", (classToFind) => {
    return Cypress.$(classToFind).length>0
})

Then in your tests:

if (cy.checkIfClassExists('.okrSelectorSelect__value-container')) {
    //do something
} else {
    //do nothing 
}
about 4 years ago · Santiago Trujillo Denunciar

0

I usually do the same like you but it would be more pretty to create a custom command for it like this:

Cypress.Commands.add("clickIfExists",(containerId , ItemId)=>{
  cy.get('body').then($body => {
    if ($body.find(containerId).length > 0) { 
      cy.get(ItemId).click();
    }
  }); 
})

and by this way you can always call it like that if you would like to click on .okrSelectorSelect__option :

cy.clickIfExists(".okrSelectorSelect__value-container",".okrSelectorSelect__option")
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda