我已经MyStyledButton基于material-ui 编写了一个自定义按钮()Button。
import React from "react";
import { Button } from "@material-ui/core";
import { makeStyles } from "@material-ui/styles";
const useStyles = makeStyles({
  root: {
    minWidth: 100
  }
});
function MyStyledButton(props) {
  const buttonStyle = useStyles(props);
  const { children, width, ...others } = props;
  return (
      <Button classes={{ root: buttonStyle.root }} {...others}>
        {children}
      </Button>
     );
}
export default MyStyledButton;它使用主题进行样式设置,并且backgroundColor将设置为黄色阴影(具体而言#fbb900)
import { createMuiTheme } from "@material-ui/core/styles";
export const myYellow = "#FBB900";
export const theme = createMuiTheme({
  overrides: {
    MuiButton: {
      containedPrimary: {
        color: "black",
        backgroundColor: myYellow
      }
    }
  }
});
该组件在我的main中实例化,index.js并包装在中theme。
  <MuiThemeProvider theme={theme}>
     <MyStyledButton variant="contained" color="primary">
       Primary Click Me
     </MyStyledButton>
  </MuiThemeProvider>如果我检查Chrome DevTools中的按钮,则按background-color预期进行“计算”。Firefox DevTools中也是如此。
然而,当我写个笑话测试,以检查background-color和使用我查询DOM节点样式的按钮,getComputedStyles()我得到的transparent背部和测试失败。
const wrapper = mount(
    <MyStyledButton variant="contained" color="primary">
      Primary
    </MyStyledButton>
  );
  const foundButton = wrapper.find("button");
  expect(foundButton).toHaveLength(1);
  //I want to check the background colour of the button here
  //I've tried getComputedStyle() but it returns 'transparent' instead of #FBB900
  expect(
    window
      .getComputedStyle(foundButton.getDOMNode())
      .getPropertyValue("background-color")
  ).toEqual(myYellow);我提供了一个CodeSandbox,其中包含确切的问题,最少的代码可重现和JEST测试失败。
                  .MuiButtonBase-root-33 background-color是透明的,而.MuiButton-containedPrimary-13不透明-因此问题是,CSS中的类同等重要,因此仅加载顺序可以区分它们->测试样式中的加载顺序错误。
                
                
                  
                    —
                    Zydnar 
                    
                  
                
              
                  @Andreas-根据要求更新
                
                
                  
                    —
                    Simon Long 
                    
                  
                
              
                  @Zyndar-是的,我知道。有什么办法可以使该测试通过?
                
                
                  
                    —
                    西蒙·朗
                    
                  
                
              
                  会不会在
                
                  
                    —
                    Brett DeWoody 
                    
                  
                
              theme在测试中使用的需要?如在中,将包裹<MyStyledButton>在<MuiThemeProvider theme={theme}>?中。还是使用一些包装函数将主题添加到所有组件?
                
                  不,那没有任何区别。
                
                
                  
                    —
                    西蒙·朗
                    
                  
                
              