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

486
Visualizações
Cypress: How to save CSS color to a variable?

I am having trouble finding a way to save a CSS color value to a variable using Cypress in my React app.

I understand the assertions fine:

cy.get('myElement').should('have.css', 'color').and('eq', 'rgb(255, 255, 255)')

The problem is the element I am trying to test can potentially be two different colors on page load, so I cannot assert for one color since the other may be true, and both are considered vald.

What I would like is to be able to store the current color into a variable so I know which color I should assert.

Like:

var color = cy.get('myElement').should('have.css', 'color')

if(color === 'rgb(255, 255, 255)') {
    //assert color to be white
}
else {
    //assert color to be black
}

or:

var color = null
cy.get('myElement').then(($element) => {
    color = $element.color()
})

if (color === 'rgb(255, 255, 255)') {
   //assert color to be white
}
else {
   //assert color to be black
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You almost have it, but need to use .then() or a .should() after the Cypress commands, which do not give you anything useful when you assigning to a variable (the first code block)

cy.get('myElement').should('have.css', 'color')
  .should(color => {
    const white = 'rgb(255, 255, 255)'
    const black = 'rgb(0,0,0)'
    const chartreuse = 'rgb(127, 255, 0)'
    expect(color).to.be.oneOf([white, black, chartreuse])
  }

or

const white = 'rgb(255, 255, 255)'
const black = 'rgb(0,0,0)'
const chartreuse = 'rgb(127, 255, 0)'

cy.get('myElement')
  .should('have.css', 'color')
  .and('be.oneOf', [white, black, chartreuse])

The second code block is assigning color value correctly, but the timing is wrong - the if()...else runs before the value is assigned. Also use a .then() to correct the timing

let color
cy.get('myElement').then(($element) => {
  color = $element.css('color')
})

// other commands...

cy.then(() => {
  expect(color).to.be.oneOf([white, black])
})

Or assign the color value to an alias (but you also access the alias value from a .then()).

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