testing-library / jest-dom

:owl: Custom jest matchers to test the state of the DOM
https://testing-library.com/docs/ecosystem-jest-dom
MIT License
4.44k stars 401 forks source link

toHaveStyles doesn't work with a CSS variable #649

Open thany opened 3 weeks ago

thany commented 3 weeks ago

Relevant code or config:

render(<Button color="primary" />);
const button = screen.getByRole('button');
expect(button).toHaveStyle({ 'background-color': '#3E8800' });

Button is an MUI Button, but it doesn't matter, as the repro will show.

What you did:

The button background is declared in CSS with a variable.

What happened:

The unittest claims the background color as being ButtonFace rather than literally anything sensible.

Reproduction:

https://codesandbox.io/p/sandbox/5z6x4r7n0p (edit: whoops) https://codesandbox.io/p/sandbox/react-testing-library-demo-forked-kkn5xt

Problem description:

The toHaveStyles assertion is not parsing CSS variables correctly, or at all. It seems to work with sort of a user agent default or something. CSS variables cause similar issues when used on (and testing for) other CSS properties.

Suggested solution:

I don't know if this is related to years-old issues about toHaveStyle and css variables, so it's possible the problem is just returned from the dead and back with revenge (maybe a bit less dramatic), or this is a totally new issue.

The point is, a CSS var should be parsed and resolved, so a unittest can test for the value that would be visible. I'm not sure if this is a helpful suggestion though, because it seems quite obvious, but perhaps CSS vars were never a consideration in the first place.

jeremy-davis-sonarsource commented 1 week ago

Hi thany, I think the reproducer link isn't correct:

hello.js

export default ({ name }) => <h1>Hello {name}!</h1>;

tests/hello.js

test('React Testing Library works!', () => {
  const {getByText} = render(<Hello name="Jill" />)
  expect(getByText(/hello jill/i)).toBeInTheDocument()
})
thany commented 1 week ago

I think this is it: https://codesandbox.io/p/sandbox/react-testing-library-demo-forked-kkn5xt

The share button in codesandbox doesn't work properly 😑

In the mean time, were you not able to reproduce the problem going off my description?

jeremy-davis-sonarsource commented 1 week ago

That link works! I haven't tried to be honest, I'm not a contributor :sweat_smile: I have a similar problem and I wanted to check if it's the same. I believe it's not: in my case, the test passes with any value.

Guess I'll create my own issue...

thany commented 1 week ago

I haven't tried to be honest, I'm not a contributor 😅

Sorry, I guess I was making assumptions 😀

Anyway thanks for noticing my original mistake.