Can someone provide guidance on how to validate a HEX color in Cypress?

As I dive into testing with Cypress, my lack of experience has become apparent. I am trying to test the background-color CSS property on a specific element, but running into an issue - everything is in RGB format behind the scenes, while I need to work with HEX values. This has left me wondering if there's a way around this, or if some sort of translation will be necessary.

cy.get('#button-login')
   .should('have.css', 'background-color', "#6a7ba3")

ERROR :

...to have CSS property 'background-color' with the value '#6a7ba3', but the value was 'rgb(106, 123, 163)'

Answer №1

To accomplish your goal, utilize the chai-colors assertion plugin.

Installation instructions:

npm install chai-colors

Next, incorporate this into your code:

import chaiColors from 'chai-colors'
chai.use(chaiColors)

Alternatively, use this if needed:

var chaiColors = require('chai-colors');    
chai.use(chaiColors);

You can now write your assertions in this manner:

cy.get('#button-login')
  .should('have.css', 'background-color')
  .and('be.colored', '#6a7ba3')

Answer №2

Encountering an issue with chai-colors, I opted to switch to the tinycolor2 library for color assertion in my code snippet below:

import Toast from './index';

import { themedMount } from '../../../cypress/index';
import tinycolor from 'tinycolor2';

const toastColorMap: Record<string, string> = {
  success: '#cff5c4',
  error: '#fbcfc8',
};
const toasts = [
  { _id: '1', message: 'success toast notification', type: 'success' },
  { _id: '2', message: '2 success toast notification', type: 'error' },
  { _id: '3', message: 'error toast notification', type: 'error' },
];
describe('Toast.cy.tsx', () => {
  it('Rendering of Toast component with toasts is correct', () => {
    themedMount(<Toast toasts={toasts} />);
    toasts.forEach((t) => {
      const toastElement = cy.contains(t.message);
      toastElement.should('have.css', 'background-color').then((bg) => {
        const color = tinycolor(bg);
        expect(color.toHexString()).equal(toastColorMap[t.type]);
      });
    });
  });
});

Answer №3

I have completed the initial step by implementing my function (convert hex to rgb) in the commands.ts file.

 export const hexToRgb = (hex: string) => {
  let r = 0;
  let g = 0;
  let b = 0;

  // Handling 3-digit hex color codes
  if (hex.length === 4) {
    r = parseInt(`${hex[1]}${hex[1]}`, 16);
    g = parseInt(`${hex[2]}${hex[2]}`, 16);
    b = parseInt(`${hex[3]}${hex[3]}`, 16);

  // Handling 6-digit hex color codes
  } else if (hex.length === 7) {
    r = parseInt(hex.slice(1, 3), 16);
    g = parseInt(hex.slice(3, 5), 16);
    b = parseInt(hex.slice(5, 7), 16);
  }
  // Returning RGB value with spaces between values
  return `rgb(${r}, ${g}, ${b})`;
};

Moving on to the next step,

import {
hexToRgb,
} from '../../support/commands';

it('Ensuring correct colors for elements', () => {
cy.get(byTestId('admin-roll-up-menu')).click();
cy.get(byTestId('link-to-companies')).click();

testLoadPage('select-company-btn-3', '/accountant/overview');
cy.wait('@authSwitchCompany').should(({ request }) => {
  expect(request.body.companyId, 'companyId').to.eq(3);
});
defualControllerColorsLight();
cy.get(byTestId('overview-graph')).should(
  'have.css',
  'background-color',
  hexToRgb('#ffffff'),
);
cy.get(byTestId('graph-title')).should(
  'have.css',
  'color',
  hexToRgb('#292929'),
); 
});

The expected result can be viewed here.

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

JavaScript for switching between grid layouts

I have organized 3 DIVs using a grid layout. There is a Navigation bar with an on-click event attached to it. When a button on the nav-bar is clicked, I want the JavaScript function to display the corresponding grid associated with that button. Currently, ...

Node.js program experiences issues with incorporating netCDF files

I am attempting to encode a NetCDF file within my Node.js program using the netcdf library, which can be found at https://www.npmjs.com/package/netcdf. After running the program, I encountered the following error: C:\app [master +2 ~1 -0 !]> npm ...

What is the most effective way to incorporate the DOMContentloaded event listener into the document using nextJS?

I am working on integrating an HTML code snippet into my Next.js project. The snippet includes an external script with a createButton function. <div id="examplebtn"></div> <script type="text/javascript"> //<![ ...

Understanding which page is being rendered through _app.js in React/Next.js is crucial for seamless navigation and

Currently, I am working on rendering my web navigation and footer on my _app.js file. My goal is to dynamically adjust the style of the navigation and footer based on the specific page being accessed. Initially, I considered placing the navigation and foot ...

"Is there a way to retrieve the props that have been passed down to a

I am looking to have custom props created in the root layer of my React app: import React from 'react' import App, { Container } from 'next/app' export default class MyApp extends App { static async getInitialProps({ Component, rout ...

Creating a new JavaScript object using a Constructor function in Typescript/Angular

Struggling with instantiating an object from an external javascript library in Angular/Typescript development. The constructor function in the javascript library is... var amf = { some declarations etc } amf.Client = function(destination, endpoint, time ...

Mastering data extraction from JSON using React JS (with Axios)

Being new to ReactJS and axios, I am facing a challenge. I need to iterate through JSON data and extract values where the key is a number (e.g. 0, 1, 2...). However, I am unsure how to implement this in my code since the server provides dynamic JSON data ...

AngularJS animate issue: TypeError - method 'classNameFilter' not found

When I added ngAnimate to my AngularJS app.js file as documented, I encountered a peculiar error: Object [object Object] has no method 'classNameFilter' - angular-animate.js:297 Any idea why this is happening? This is the code snippet where I ...

Using static methods within a static class to achieve method overloading in Typescript

I have a TypeScript static class that converts key-value pairs to strings. The values can be boolean, number, or string, but I want them all to end up as strings with specific implementations. [{ key: "key1", value: false }, { key: "key2&qu ...

How can Array.map() be combined with D3 selection?

Is there a way to calculate the maximum length of text elements in an SVG selection similar to using Array.map()? Currently, I am retrieving the maximum length of a selection of SVG <text/> elements by utilizing .selectAll(...)[0].map(...), but it fe ...

Is it possible to retrieve the final digit from a URL using NUXT/Vue?

My dilemma involves utilizing the SWAPI API to display a single result, whether it be a person or a planet. However, instead of providing a direct ID for each item, the API returns a complete URL in this format: "url": "http://swapi.dev/api/ ...

The utilization of the "notFound" prop within getStaticProps does not influence the HTTP status code returned by the page

I recently set up a fresh Next.js application and created the following page: // /pages/articles/[slug].js import React from 'react' import { useRouter } from 'next/router' import ErrorPage from 'next/error' const Article = ...

The configuration for CKEditor5's placeholder feature seems to be malfunctioning

I am currently experimenting with a customized version of CKEditor 5 known as BalloonBlockEditor. Below is the custom build output that I have created: /** * @license Copyright (c) 2014-2023, CKSource Holding sp. z o.o. All rights reserved. * For licens ...

Passing a variable from index.html to a script in Angular

I am attempting to pass the array variable 'series' to the script in HTML. Is there a way to do this? app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app ...

What is the best way to access a reference to the xgrid component in @material-ui?

Is there a way to obtain a global reference to the xgrid component in order to interact with it from other parts of the page? The current code snippet only returns a reference tied to the html div tag it is used in, and does not allow access to the compo ...

What is the best way to ensure that each service call to my controller is completed before proceeding to the next one within a loop in Angular?

Calling an Angular service can be done like this: this.webService.add(id) .subscribe(result => { // perform required actions }, error => { // handle errors }); // Service Definition add(id: number): Observable < any > { retu ...

What causes Three.js OBJ conversion to render as mesh successfully but log as undefined?

I'm just getting started with Three.js and I'm experimenting a lot. Although I'm new to Javascript as well, the issue I'm facing seems to be more about variable scoping and callback function protocols than it is about Three.js itself... ...

"Utilizing Bootstrap Modal for efficient AJAX saving of multiple records with the help of bootstrapValidator

I'm encountering an issue with a bootstrap modal form and validation using bootstrapValidator. The problem I'm facing is that when I open the modal, fill out the fields, close it, reopen it, refill the fields, and submit the form, my script inser ...

German-formatted jQuery datepicker

Need help in changing jQuery datepicker formatting from MM/DD/YYYY to German style as d MMMM yyyy. Tried implementing the following code but encountering issues. <script type="text/javascript"> $(function () { $('.datepicker&ap ...

Error in MUI: Unable to access undefined properties (reading 'drawer')

Recently, I encountered an unexpected error in my project using MUI v5.0.2. Everything was working fine just a week ago with no errors, but now I'm facing this issue without any changes made to the code: Error: TypeError: Cannot read properties of un ...