测试功能组件中的功能

问题描述

我创建了一个卡片组件并为此编写了测试用例,但是在查看测试覆盖率编号时,我发现该组件的分支覆盖率为50%。测试用例中缺少的部分是onPress函数中其他部分的测试。

Q1。如何测试缺少的部分并扩大覆盖范围?

第二季度。如何分别测试Card组件的onPress功能?

const Card = (props) => {

    const onPress = () => {
        if (props.onPress) props.onPress();
    };

    return (<TouchableWithoutFeedback onPress={onPress}>
        <View style={[Style.body,{ width: props.width,height: props.height }]}>
            <ImageBackground source={{ uri: props.imageUrl }} style={{ width: '100%',height: '100%' }} />
        </View>
    </TouchableWithoutFeedback>);
};

export default Card;

解决方法

您有两种情况:

  1. props.onPress已定义,因此到达了if下的代码。
  2. props.onPress未定义,因此if下的代码未定义。

道具是您控制它的变量,因此您可以根据需要传递道具。只要通过涵盖这两种情况的道具,您就会满足所需的条件。

我认为您不需要测试孤立的onPress函数。但是另一种方法是从组件中删除逻辑。

export const onPress = (props) => () => {
    if (props.onPress) {
        props.onPress()
    }
}

const Card = (props) => {

    return (<TouchableWithoutFeedback onPress={onPress(props)}>
        <View style={[Style.body,{ width: props.width,height: props.height }]}>
            <ImageBackground source={{ uri: props.imageUrl }} style={{ width: '100%',height: '100%' }} />
        </View>
    </TouchableWithoutFeedback>);
};

export default Card;

现在,您已导出了onPress函数,可以根据需要进行测试。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...