如何测试使用 Material UI makeStyles() 制作的条件样式?

How to test conditional styling made with 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() 分配了一些每个组件的随机类名 makeStyles-component-12。我还注意到具有相同样式的组件具有不同的类名。所以那是不行的。

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

非常感谢。

虽然不建议将您的测试与特定的 class 或 css 样式结合使用,但您可以使用 jest-dom.toHaveStyle 匹配器来测试是否正确的样式传递相应的道具时应用。