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

What is the best way to activate a modal in the parent component when a button is clicked in the child component?

Currently I have the following setup: panelHeader.vue (which is a child component) index.vue (the parent component where my main list view is) panelHeader.vue <template> <v-row> <div class="panelHeader"> ...

When you try to create a popover, a cautionary message pops up indicating that $tooltip is no longer supported. It is

I need help with creating a popover that appears when hovering over an anchor tag. Here is the code I am using: angular: 1.4.2 ui-bootstrap :0.14.2 <div class="row" ng-repeat="endorsement in endorsements| filter: {category:categorySelected}"> &l ...

Toggle the sidebars to slide out and expand the content division using JavaScript

I am looking to achieve a smooth sliding out effect for my sidebars while expanding the width of the middle content div. I want this action to be toggled back to its original state with another click. Here's what I've attempted so far: $(' ...

What could be causing my bootstrap-switch to malfunction?

Here is the snippet of code I am working with: jQuery.each($('.onoffswitch-checkbox'), function(i, slotData) { console.log($(slotData).bootstrapSwitch('state')) }) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1 ...

Customize the label of the model in AngularStrap's typeahead ng-options to display something

Utilizing AngularStrap typeahead for address suggestions, I am facing an issue where I want to set the selected address object as my ng-model, but doing so causes me to lose the ability to display just one property of the object as the label. Here is an e ...

In order to determine if components linked from anchor elements are visible on the screen in Next.js, a thorough examination of the components

Currently, I am in the process of developing my own single-page website using Next.js and Typescript. The site consists of two sections: one (component 1) displaying my name and three anchor elements with a 'sticky' setting for easy navigation, a ...

javascript design pattern - achieving unexpected outcome

In the code snippet provided, the variable a is turning out to be undefined. Are you expecting it to display the parameter value passed in the parent function? function test(a) { return function(a) { console.log('a is : ' + a); // Ou ...

Creating a Breeze js entity using a JSON string and importing it into the breeze cache: A step-by-step guide

Currently, I am developing a mobile single page website that utilizes technologies like breeze js, angular js, web API, and entity framework. To enhance the performance of the site, I have decided to include the breeze metadata in a bundled JavaScript fil ...

What's the scoop on NodeJS, Express, Nginx, and Jade?

Currently exploring options for technologies and libraries to use in a new, large-scale project. With knowledge of NodeJS, JavaScript, Express, and Jade (now Pug), my team and I are leaning towards adopting these for the project. The main issue we're ...

Arranging numerous items based on date in JavaScript without prior knowledge

I'm facing an issue where I need to showcase JSON data containing events but want them sorted by time. The challenge is that the number of objects in the JSON can vary as users can keep adding more. Below is my code snippet demonstrating how the displ ...

Understanding the Submission of a Form upon the submission event

On my form, I have multiple buttons - two of them use ajax to submit the form and clear it for adding multiple records, while the last button is for moving onto the next page. I'm wondering if jQuery's .submit() method can determine how the form ...

The text becomes distorted and unreadable after the function is applied. It is impossible to decipher the message

There is a function called getResourceText(''), which takes a key as an argument. This function provides a translation of the requested text when it is called. setFilterName = (isFilterChanged, buttonId, filterName) => { switch (filterName ...

Leveraging jQuery's element objects and the :contains selector allows for powerful

I need to search for a link that contains the word 'gathered'. Although I understand how to do it logically, I am having trouble writing the jQuery syntax for the selector: if (index === 3) { var $link = $('#rest').find('.tr ...

Navigating a Multi-Page Website with Sleek Scrolling

I've been searching for a solution everywhere but haven't had any luck. I'm trying to implement a smooth scroll effect that works seamlessly across multiple pages. For instance, the smooth scroll effect is present on the homepage with naviga ...

Incorporating a Script into Your NextJS Project using Typescript

I've been trying to insert a script from GameChanger () and they provided me with this code: <!-- Place this div wherever you want the widget to be displayed --> <div id="gc-scoreboard-widget-umpl"></div> <!-- Insert th ...

Divide the sentence using unique symbols to break it into individual words, while also maintaining

Is there a way to split a sentence with special characters into words while keeping the spaces? For example: "la sílaba tónica es la penúltima".split(...regex...) to: ["la ", "sílaba ", "tónica ", "es ", "la ", "penúltima"] ↑ ...

What is the best way to incorporate several functions within a resize function?

Is it possible to incorporate multiple functions within the windows.width resize function? I have been experimenting with some code, but I would like to restrict its usage to tablet and mobile devices only, excluding laptops and PCs. Any suggestions on h ...

"Problem with AngularJS: Unable to display data fetched from resource using ng-repeat

I am currently working on an AngularJS application that retrieves data from a RESTful API using $resource. However, I have encountered an issue where the view is not updating with the data once it is received and assigned to my $scope. As a beginner in An ...

Combining Arrays in AngularJS: A Step-by-Step Guide

I have two arrays with dynamic values: $scope.objectName = [{ Name: '' }]; $scope.propertiesElement = [{ Key: '', Value: '' }]; How can I concatenate these arrays to achieve the following result? [{Name:''},{ Key: ...

JavaScript can be used to open several tabs simultaneously within a single browser window

Looking to open multiple tabs in the main browser? Check out this code snippet: function openSM() { window.open("http://www.google.com","_blank"); window.open("http://www.yahoo.com","_blank"); window.open("http://www.bing.c ...