Skip to content

toHaveStyles doesn't work with a CSS variable #649

@thany

Description

@thany
  • @testing-library/jest-dom version: 6.6.2
  • node version: 20.18.0
  • vitest version: 2.1.3
  • npm version: 10.9.0

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions