Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

152
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda