reactjscypressvalue-of-css-property

How to test a component HSL background color in cypress? ( Typescript )


I'm using a CSS module for my styling, and I want to test the background color of the button, but it's in hsl not RGB.

I have seen people struggle with the same issue, but they found solutions like chai-color or color libraries. The problem is I use Typescript and these libraries does not support types. How can I test my HSL background?

 it("when button rendered with type primary, should have blue color hsl(206, 100%, 42%)", () => {
    cy.mount(
      <Button
        text="Blue"
        type="primary"
      />
    );
    cy.get("button").should(
      "have.css",
      "background-color",
      "hsl(206, 100%, 42%)"
    );
  });

enter image description here


Solution

  • There is this which could be useful 30secondsofcode - RGB to HSL.

    The issue with CSS values in tests is rounding, so you may want to use closeTo matching

    const RGBToHSL = (r, g, b) => {
      r /= 255;
      g /= 255;
      b /= 255;
      const l = Math.max(r, g, b);
      const s = l - Math.min(r, g, b);
      const h = s
        ? l === r
          ? (g - b) / s
          : l === g
          ? 2 + (b - r) / s
          : 4 + (r - g) / s
        : 0;
      return [
        60 * h < 0 ? 60 * h + 360 : 60 * h,
        100 * (s ? (l <= 0.5 ? s / (2 * l - s) : s / (2 - (2 * l - s))) : 0),
        (100 * (2 * l - s)) / 2,
      ];
    }
    
    cy.get("button")
      .should($el => {
        const rgbString = window.getComputedStyle($el[0])
          .getPropertyValue("background-color")           // "rgb(0, 121, 214)"
    
        const rgbValues = rgbString.match(/rgb\([.*]\)/)[1]
                                   .split(', ').map(v => +v)   // [0, 121, 214]
    
        const hsl = RGBToHSL(...rgbValues)
    
        expect(hsl[0]).to.be.closeTo(206, 1)
        expect(hsl[1]).to.be.closeTo(100, 1)
        expect(hsl[2]).to.be.closeTo(42, 1)
      })