Is there a way to make check on HEX color - Cypress

Viewed 2064

I am currently busy with testing on Cypress . I am actually new so i am not so familiar with everything around , but i am trying to test a CSS property of background-color on certain element , but the problem is that behind the scenes everything is RGB , but i need to test on HEX . So i ask myself is there a way to do that or a translation should 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)'

2 Answers

You can achieve what you want using the chai-colors assertion plugin.

Install as follows:

npm install chai-colors

Then add this to your code:

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

Or this, as applicable:

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

Now you can write your assertion like this:

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

I was facing error with chai-colors so I used the tinycolor2 library to assert the color as follows

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('Toast component renders toasts properly', () => {
    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]);
      });
    });
  });
});
Related