如何测试使用Material UI makeStyles进行的条件样式?

问题描述

我已经在React应用程序上工作了几周,并且大部分情况下我都使用Material UI组件。

我有这个组件,它的样式根据其道具的值而有所不同。为此,我做了类似的事情:

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

getComponentBackgroundColor()被定义为

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

,然后设置组件的className

我的问题是,我想测试该组件以确保正确应用样式(某些getStyle()方法要比检查道具是否存在更复杂)。

我正在使用react-testing-library,我的第一个直觉是检查渲染的组件是否具有正确的className,但经过进一步检查,我意识到makeStyle()分配了一些随机的className就像makeStyles-component-12一样。我还注意到具有相同样式的组件具有不同的className。所以那是不行的。

使用Material UI的makeStyles()时是否有一种简单的方法来测试条件样式?

谢谢。

解决方法

尽管不建议将测试与特定的类或CSS样式结合使用,但是您可以使用jest-dom.tooltip { position: relative; display: inline-block; text-align: center; } .tooltip .tooltiptext { visibility: hidden; width: 120px; background-color: black; color: #fff; text-align: center; border-radius: 6px; padding: 5px 0; /* Position the tooltip */ position: absolute; z-index: 1; } .tooltip:hover .tooltiptext { visibility: visible; }匹配器来测试通过相应道具时是否应用了正确的样式。