【问题标题】:Testing function in a functional component在功能组件中测试功能
【发布时间】:2020-12-18 23:31:34
【问题描述】:

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

第一季度。如何测试这个缺失的部分并增加我的覆盖率?

第二季度。如何单独测试 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;

【问题讨论】:

  • 写一个测试,其中props.onPress 是假的。如果您想对 onPress 进行单元测试,请将其移至顶层并使用组合将 deps 馈入其中。
  • 我没听懂你的意思。你能给我示例答案或链接吗?

标签: javascript reactjs react-native jestjs react-test-renderer


【解决方案1】:

你有两种情况:

  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我已经测试过了。但是如何测试案例2?如果我没有在 onPress 中传递任何东西,那么我该如何测试?
  • 正如我所说,只需操纵道具以使 onPress 未定义。断言是否在需要时没有发生某些事情,因此也具有价值。
  • 1) 你没有通过props.onPress 2) 你模拟点击TouchableWithoutFeedback 3) 如果由于未捕获的异常而导致测试失败
  • @CFLS 我同意你的解耦方法。但我不确定这是否是编写测试用例的最佳实践
猜你喜欢
  • 2020-07-17
  • 2019-08-06
  • 2021-08-18
  • 2019-07-22
  • 1970-01-01
  • 2021-08-30
  • 1970-01-01
  • 2020-09-21
  • 1970-01-01
相关资源
最近更新 更多