laurent.aubin
laurent.aubin

Reputation: 43

How to test conditional styling made with Material UI makeStyles()?

I've been working on a React app for a few weeks and I use Material UI components for most of by base.

I have this component that has its style change depending on the values of its props. To do this, I did something like:

  const useStyles = makeStyles({
    component: {
      ...
      backgroundColor: getComponentBackgroundColor(),
      ...
    }
  });

with getComponentBackgroundColor() being defined as

  const getComponentBackgroundColor = () => {
    if (props.someProp) {
      return "green";
    }
    return "red";
  };

and then by setting the component's className.

My problem is that I want to test this component to ensure that the styling is correctly applied (some getStyle() methods are more complex than juste looking if a prop exists or not).

I'm using the react-testing-library and my first instinct was to check if the rendered component had the right className, but upon further inspection, I realized that makeStyle() assigns some random className like makeStyles-component-12 to each component. I also noticed that components with the same styling had different classNames. So that was a no-go.

Is there an easy way to test conditional styling when using Material UI's makeStyles() ?

Thanks a bunch.

Upvotes: 4

Views: 1796

Answers (1)

Dobby Dimov
Dobby Dimov

Reputation: 1032

Although it's not recommended to couple your tests with specific class or css style, you could use jest-dom's .toHaveStyle matcher to test if the right style is applied when passing the corresponding props.

Upvotes: 2

Related Questions