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

138
Visualizações
Conditionally assert element values in DOM depending on it's value in backend with Cypress?

Trying to do Cypress Testing with my React app.

I'm retrieving an object with an attribute expirationDate from the backend. It's an integer with format YYYYMMDD. In my corresponding frontend in the <input> component, it's rendered as an YYYY-MM-DD string.

However the object may optionally not have an expiration date at all, which is instead represented as the attribute being -1 or -2. This is presented as an empty string '' in the <input>.

I thus need to conditionally check the value. How do I go about doing this with Cypress?

Closest I have right now is

cy.get('#input-expiration-date').should('have.value', expirationDate || '')

But this is not really an accurate test of the above conditions.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Conditional testing can be done as follows, but this is bad practice.

cy.get('#input-expiration-date')
  .invoke('val')
  .then(val => {
    
    if (val === expirationDate) {     // fails because page is still fetching
      ...
    }
  })

The test runs faster than the value can be fetched from the server.

You can avoid the issue by waiting for the object fetch with cy.intercept() and do the conditional check then.

let expirationDate = 'YYYYMMDD'

cy.intercept(url).as('object')

cy.visit(...)

cy.wait('@object').then(object => {

  if (object.expirationDate) {
    cy.get('#input-expiration-date')
      .should('have.value', expirationDate)
  }
})
about 4 years ago · Juan Pablo Isaza Relatório

0

Or if you want to check and further do some actions based on the value, you can do something like this:

cy.get('#input-expiration-date')
  .invoke('val')
  .then((val) => {
    if (val == expirationDate) {
      //Do something
    } else if (val == '') {
      // Do something
    } else {
      //Do something
    }
  })
about 4 years ago · Juan Pablo Isaza Relatório

0

you can do:

cy.get('#input-expiration-date').then(element => {
//and here you can have conditions and access the DOM element

})
about 4 years ago · Juan Pablo Isaza 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