Cypress: A guide to storing CSS color values in a variable

I'm struggling to figure out how to save a CSS color value to a variable using Cypress in my React application.

I have a good understanding of the assertions, such as:

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

The issue arises because the element I need to test could be one of two different colors when the page loads. Therefore, I cannot simply assert for one color as both are valid possibilities.

What I'd like to do is store the current color in a variable so that I can determine which color to assert against.

For example:

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

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

or:

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

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

Answer №1

While you're on the right track, make sure to include .then() or .should() after your Cypress commands. When assigning to a variable, these commands are necessary as they provide useful information (as shown in 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])
  }

Alternatively, you can use:

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 correctly assigns the color value, but the timing is off - the if()...else statement executes before the value is assigned. You can rectify this by using .then() to ensure correct timing.

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

// other commands...

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

Alternatively, you can assign the color value to an alias and access it within a .then() block.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Responsive design is achieved through the use of mobile media

I am seeking assistance with optimizing my website for mobile devices as it currently displays like the image below. Here are the solutions I have considered so far: Duplicating the 680 lines of CSS within the same document between @media only screen ta ...

React: The error message "p is not defined" is showing up in the component file due to the no-undef

In my React application, I am looking to display a list of menu items from an array and show the detailed description of each item upon clicking. The array of menu items is stored in a separate file called dishes.js. The menu items are rendered using a Me ...

What methods can I utilize to expand the qix color library with personalized manipulation features?

Utilizing the qix color library, my goal is to create specific custom manipulation functions for use in a theme. The approach I am taking looks something like this: import Color from 'color'; const primary = Color.rgb(34, 150, 168); const get ...

Coloring in Charts.js based on values

Exploring the options for Charts.js to dynamically change fill color based on positive or negative point values has intrigued me. I am in the process of creating an accounting system for a friend's new company, and I need a chart that visually repres ...

What is the best way to activate only one dropdown menu from a collection of others produced within a .map

I feel a bit lost with this issue, but I'm hoping for some guidance! Within my MenuWithDropdown Component, I've set up several dropdowns. Each dropdown is supposed to be activated with the handleClick() function. Normally, I would use this.state ...

Error loading QR code column in HTML table on tablet device

I am working on a pharmacy application that displays a HTML table with QRcodes as one of its column values. I am using the QRcode.min js library to convert the string to QRcode. json = $.parseJSON(JSON.stringify(res.d)); // console.log('data ' ...

Selectors for fake elements and neighboring siblings

I'm struggling to show my menu when the toggle checkbox is selected. I know that my .menu-container is not a sibling of the toggle element, but I'm not sure how to make it work without moving the toggle outside of the div so that .menu-container ...

Toggle the visibility of table rows by checking or unchecking a checkbox

I'm looking to enhance my code that removes table rows after a user clicks a checkbox, excluding the row with the checkbox itself. I also want to be able to show the table rows again when the checkbox is unchecked. Currently, my code successfully remo ...

Trouble with jQuery script causing initial word count issue in textarea upon page load

I have implemented a word count textarea jQuery script and I am trying to figure out how to update the word count onload to 2 when the text area initially displays "this example". Currently, it shows 0 words. Although I can set focus on it and move the c ...

The display of website content across various screens

I'm relatively new to creating websites using scripts, CSS, etc. But I feel like I'm getting the hang of it pretty well... Now I've reached a point where I want my site to look good on different screen resolutions. Currently, I have somethin ...

Switch the Drawer with the LeftIcon located in the AppBar

Greetings to all the Stackoverflow community members, I am embarking on my very first project using Material-UI with ReactJS. Successfully implemented the AppBar and Drawer functionalities (Drawer accessible through left bezel swipe). Now I am looking t ...

Changing the value in a multi-dimensional array using a specific path represented in array or any other format

In my project, I am dealing with a multidimensional array that represents a deep category tree menu. The structure of the array looks like this: this.tree = [{ "title": "1. dragon-breath", "items": [] }, { "title": "2. moiré-vision", "ite ...

Generate div elements dynamically for each object being populated in JSON using JavaScript

I have a main container that displays a list of JSON objects. Each object should be displayed as a separate DIV element with specific details, one after the other. Additionally, I have a comments section on a webpage where the details are stored in JSON f ...

No data retrieved from MEAN database search

I'm in the process of setting up communication between my Node.js server and a database in order to expand it to include an Angular frontend. I have implemented a path that sends a request to the database to retrieve all data (5 documents). I can conf ...

Encountering a NodeJS crash when executing MySQL queries

Exploring NodeJS for the first time and experimenting with MySQL. Successfully retrieving content from the database to display on my page (/test01). Encountering a crash when attempting to fetch values from the database in order to store them in a cookie ...

Why are the icon and text aligned on the same row?

I'm trying to display an icon next to some text on the same line, but it seems to only work when using the <div> tag. When I try to do the same with the <p> tag, it doesn't align properly. Can someone explain why? .container { di ...

Is there a way to ensure that a DIV element expands to the bottom of the page once scrolling has occurred?

Trying to create a webpage with a specific layout: Everything looks good, but if the content on the right goes off the page and requires scrolling, the left menu bar ("second_navbar") doesn't stretch to the end of the page. I've attempted chang ...

Utilize the double parsing of JSON information (or opt for an alternative technique for dividing the data

Looking for the most effective approach to breaking down a large data object retrieved from AJAX. When sending just one part (like paths), I typically use JSON.parse(data). However, my goal is to split the object into individual blocks first and then parse ...

React: Dynamic input field that removes default value as the user begins typing

Imagine a scenario where we have a text box in a React application with Formik and Material UI that accepts a price as a floating point number. By default, the field is set to 0. However, once the user manually enters a number, the default value should be ...

Discrepancy in Metalness Between GLTF Scene and THREE.JS Editor's Environment Available at https://threejs.org/editor/

I have encountered an issue with a gltf file. When I import it into the Three.js editor (), everything appears as expected when adding an environment map. However, when I import the same gltf file into my project scene, I notice a discrepancy in the resul ...