jest-dom: toHaveStyle Color not working as expected
dom-testing-library
version: 5.11.9react-testing-library
version: 11.2.5
Relevant code or config:
Problem Statement:
I was trying to test the styling of some components (applied via Material UI styling solution) and it seems that toHaveStyle
doesn’t work properly. The component style is computed/rendered properly in the web dom, the TabeHead cells styles show up as:
color: #fff;
background-color: #000;
But when using Testing library…
expect(screen.getByText("Calories")).toHaveStyle(`color: #FFF`);
It throws the following error: Expected - color: rgb(255, 255, 255); + color: rgba(0, 0, 0, 0.87);
rgba(0, 0, 0, 0.87)
is doesn’t match with hex #FFF
At the same time this weirdly works with background-color. Please check the code sandbox for more context, if you need further explanation let me know and Im happy to help 😃
About this issue
- Original URL
- State: open
- Created 3 years ago
- Reactions: 5
- Comments: 16 (1 by maintainers)
after struggling a lot with the toHaveStyle method, I resolved my tests converting the HEX to RGB with this function below:
your tests will look like this:
expect(screen.getByText("Calories")).toHaveStyle({ color: convertHexToRGBA('#FFF') });
This worked for me too. We didn’t upgrade any package. We just upgraded node version
I had the same problem, and for me it works to put it inside an object
expect(screen.getByText("Calories")).toHaveStyle({ color: '#FFF' });
I’m having issues getting the correct value for
background-color
for a React MUISnackbarContent
component. I’m using testing-library. I’ve confirmed that my element is the correct element and that the background color of the element isrgb(230, 243, 250)
in the inspector.Here is my test code:
Here is the error message:
I’ve also attempted using the color converter mentioned above but this results in the test passing no matter what color I pass to the function.
Hey thanks @gnapse Yes I guess is somehow related with how MUI theming/styling is applied… I’ll try to do some research in the next days about it 😃