【发布时间】:2020-01-11 15:01:24
【问题描述】:
我正在尝试达到 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 是一个具有 2 种类型的对象:浅色和深色。 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 jestjs react-testing-library