Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Testing color property always yields rgb() value, even when stored as hex #2186

Open
kylemh opened this issue Jul 20, 2018 · 17 comments
Open
Labels
existing workaround pkg/driver This is due to an issue in the packages/driver directory prevent-stale mark an issue so it is ignored by stale[bot] type: enhancement Requested enhancement of existing feature

Comments

@kylemh
Copy link

kylemh commented Jul 20, 2018

Firstly, I ❤️ Cypress. Thank you so much for all of y'alls work.

Current behavior:

I have a quick test to ensure that some branding is working within a component:

cy.get('[data-testid="StepsCard"]')
  .find('h2')
  .should('have.css', 'color').and('equal', '#663399');

This is what the property looks like in the Cypress Test Runner's browser's dev tools:
screen shot 2018-07-20 at 11 48 19 am

The test fails with the following error:
screen shot 2018-07-20 at 11 51 58 am

I've also seen others complain about this behavior: https://gitter.im/cypress-io/cypress?at=5b4da9d88fe2780689bc20e7

Desired behavior:

Test passes when running yarn cypress:open, since the <h2> element within the StepsCard component does indeed have a color of #663399.

Steps to reproduce:

I'll reproduce if absolutely necessary. I'm curious to know if perhaps this may be unavoidable. I understand y'all are very busy - feel free to close this issue if it isn't up to the necessary standard 👍

Versions

  • macOS High Sierra v0.13.6
  • Chrome v67.0.3396.99
  • Cypress v3.0.1
  • React v16.4.1
@jennifer-shehane
Copy link
Member

This assertion method comes from chai-jquery, which makes assertions off of the computed values of css styles. Unfortunately, this returns in the rgb format - and I agree, it is annoying.

As a workaround you could include some sort of hex -> rgb converter for your assertions, otherwise we will have to include one in our library and overwrite this assertion.

@jennifer-shehane jennifer-shehane added the type: feature New feature that does not currently exist label Jul 20, 2018
@kylemh
Copy link
Author

kylemh commented Jul 20, 2018

Cool. I figured it had something to do with that old jQuery issue...

I - personally - would love to see that accepted as a core feature.

Curious to see how others feel.

@j-arens
Copy link

j-arens commented Aug 14, 2018

+1

Not a big deal, but it would be nice to have this someday!

@ziyailkemerogul
Copy link

I've just noticed this issue but as @j-arens mentioned above, it's not a big deal, nice to have ;)

@jennifer-shehane jennifer-shehane added stage: ready for work The issue is reproducible and in scope priority: minor 🎗 labels Dec 4, 2018
@Roralee
Copy link

Roralee commented Dec 18, 2018

+1

Yes, its NBD, but killing dev kruft is always welcome.

@calvinballing
Copy link
Contributor

Additionally, these are compared as a string, so "rgb(255, 255, 255)" <> "rgb(255,255,255)". When I'm comparing colors, I care about the resolved color only, not the string it's encoded as.

@jennifer-shehane jennifer-shehane added the pkg/driver This is due to an issue in the packages/driver directory label Jan 29, 2019
@mutoe

This comment has been minimized.

@mutoe
Copy link

mutoe commented Aug 1, 2019

I currently use this method to compare color values. (With the color library)

import Color from 'color'

const expectBackgroundColor = Color('#000').string() // => got "rgb(0, 0, 0)"
cy.get('div').should($div => {
  const style = window.getComputedStyle($div[0])
  expect(style.backgroundColor).to.equal(expectBackgroundColor)
})

@rienheuver
Copy link

Now with css-variables this could certainly come in handy. I'm currently doing a comparison like:
expect('div').to.have.css('color', 'var(--success-color)');
which fails because the value is actually some rgb value

@NicholasBoll
Copy link
Contributor

Perhaps try the following: https://gist.github.com/NicholasBoll/e584991b36986a85acf0e95101752bc0

The gist has the following JS to add to your cypress/support/commands.js file:

const compareColor = (color, property) => (targetElement) => {
    const tempElement = document.createElement('div');
    tempElement.style.color = color;
    tempElement.style.display = 'none'; // make sure it doesn't actually render
    document.body.appendChild(tempElement); // append so that `getComputedStyle` actually works
  
    const tempColor = getComputedStyle(tempElement).color;
    const targetColor = getComputedStyle(targetElement[0])[property];
  
    document.body.removeChild(tempElement); // remove it because we're done with it
  
    expect(tempColor).to.equal(targetColor);
};

Cypress.Commands.overwrite('should', (originalFn, subject, expectation, ...args) => {
    const customMatchers = {
        'have.backgroundColor': compareColor(args[0], 'backgroundColor'),
        'have.color': compareColor(args[0], 'color'),
    };
  
    // See if the expectation is a string and if it is a member of Jest's expect
    if (typeof expectation === 'string' && customMatchers[expectation]) {
        return originalFn(subject, customMatchers[expectation]);
    }
    return originalFn(subject, expectation, ...args);
});

You'll then be able to do things like:

cy.get('button').should('have.color', 'black')
cy.get('button').should('have.color', '#000000')
cy.get('button').should('have.color', 'rgba(0, 0, 0)')

cy.get('button').should('have.backgroundColor', '#cccccc')

It works by using getComputedStyle on both the subject element and creates a temp element to get the computed color and compares. The assertion output could be better, but perhaps that's an assertion plugin?

@jennifer-shehane jennifer-shehane added existing workaround type: unexpected behavior User expected result, but got another and removed type: feature New feature that does not currently exist labels Jul 14, 2020
@ahnpnl
Copy link

ahnpnl commented Aug 2, 2021

I hope this feature will be supported soon

@YakinRojinegro
Copy link

Any progress in this one? The solution of @NicholasBoll is not working anymore in some versions due to the change of rgb to rgba in cypress these are the same color (white).
image

@Tooluloope
Copy link

Any Luck on this.

@drecali
Copy link

drecali commented Mar 1, 2022

@YakinRojinegro @Tooluloope
This answer on Stack Overflow works for me. Basically the chai-colors plugin can compare colors expressed in any standard CSS color model. I use it to compare HEX to RGBA. Hope that helps!

@cypress-bot cypress-bot bot added stage: backlog and removed stage: ready for work The issue is reproducible and in scope labels Apr 29, 2022
@nagash77 nagash77 added the prevent-stale mark an issue so it is ignored by stale[bot] label Apr 3, 2023
@alaaahmedmu
Copy link

any progress on this issue?

@vsambor
Copy link

vsambor commented Nov 17, 2023

This is very annoying :(

@jennifer-shehane jennifer-shehane added type: enhancement Requested enhancement of existing feature and removed type: unexpected behavior User expected result, but got another stage: backlog labels Nov 28, 2023
@katzohub
Copy link

@jennifer-shehane thanks for the idea 💯
my function here (convert hex to rgb) is in place file commands.ts

      export const hexToRgb = (hex: string) => {
      let r = 0;
      let g = 0;
      let b = 0;
    
      // 3 digits
      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);
    
    // 6 digits
    
      } 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);
      }
      // return rgb value , alert on space
      return `rgb(${r}, ${g}, ${b})`;
    };

and next step

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

 it('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'),
    );
  });

and result

cy_result_git

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
existing workaround pkg/driver This is due to an issue in the packages/driver directory prevent-stale mark an issue so it is ignored by stale[bot] type: enhancement Requested enhancement of existing feature
Projects
None yet
Development

No branches or pull requests