如何在带有Jest的React中测试此行?

问题描述 投票:0回答:1

我正在尝试达到100%的测试覆盖率,而且我只是不知道如何测试一行。谁能帮我?我正在使用Jest,React-testing-library和ReactJS。

由于我想变得更好地进行测试,所以我也希望能对如何测试该行进行解释。

const LatestDataListItem = props => {
  const getThemeTone = useThemeTone(); /* this hooks is simply returning a string(whick can be dark or light) */
  return (
      <StyledItem {...props}>
        <StyledValue
          primaryTextProps={{
            style: {
              fontSize: '32px',
              color: isCaution(props) /* this is what i'm trying to cover */ 
                ? getCautionColorByTheme(getThemeTone).red
                : getCautionColorByTheme(getThemeTone).blue
            }
          }}
        />
      </StyledItem>
  );
};

评论行是我要测试的内容:

color: isCaution(props) 
? getCautionColorByTheme(getThemeTone).red : getCautionColorByTheme(getThemeTone).blue

这是isCaution功能:

const isCaution = ({ caution }) => {
  return true; /* returning true only to make easier to post here */
};

这是getCautionColorByTheme

const colorsByThemeTone = {
  light: {
    blue: '#0d3459',
    red: '#f2463d',
    lightRed: 'rgba(255, 0, 0, 0.07)'
  },
  dark: {
    blue: '#e8e8e8',
    red: '#fa5a4b',
    lightRed: '#fa5a4b'
  }
};

const getCautionColorByTheme = themeTone => {
  return colorsByThemeTone[themeTone];
};

因此发生的是,colorsByThemeTone是具有两种类型的对象:浅色和深色。如果主题是深色或浅色,则getThemeTone返回,这就是我获得颜色的方式。

[我当时想也许我需要导出getCautionColorByTheme以导入我的.test.js文件并在内部测试此功能,但我不知道该怎么做。

这是我尝试过的:

  it('should render the test getCautionColorByTheme receiving light theme', () => {
    const colorsByThemeTone = {
      light: {
        blue: '#0d3459',
        red: '#f2463d',
        lightRed: 'rgba(255, 0, 0, 0.07)'
      },
      dark: {
        blue: '#e8e8e8',
        red: '#fa5a4b',
        lightRed: '#fa5a4b'
      }
    };
    const result = getCautionColorByTheme('light');
    expect(result).toMatchObject(colorsByThemeTone.light);
  });

谢谢!

reactjs testing jest react-testing-library
1个回答
0
投票

我建议将getCautionColorByTheme()设为纯函数:

const getCautionColorByTheme = ({
  themeTone,
  colorsByThemeTone = {
    light: {
    blue: '#0d3459',
    red: '#f2463d',
    lightRed: 'rgba(255, 0, 0, 0.07)'
  },
  dark: {
    blue: '#e8e8e8',
    red: '#fa5a4b',
    lightRed: '#fa5a4b'
  }
 }
}) => colorsByThemeTone[themeTone]

[如果还没有,也可以使isCaution()纯净。这样,您可以隔离测试逻辑。

© www.soinside.com 2019 - 2024. All rights reserved.