Testing function in a functional component

235 Views Asked by At

I have created a card component and has written test cases for this but on looking into test coverage number I found branch coverage for this component is 50%. And the part which is missing under test cases is testing of else part in onPress function.

Q1. How can I test this missing part and increase my coverage?

Q2. How can we test onPress function of Card component individually?

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

There are 1 best solutions below

4
On

You have two scenarios:

  1. props.onPress is defined, so the code under the if is reached.
  2. props.onPress is not defined, so the code under the if is not defined.

Props is a variable that you control it, so you can pass the props as you want/need. Just pass the props covering this two scenarios and you are good with the conditions needed.

I don't think you need to test the onPress function isolated. But an alternative would be remove the logic from the component.

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;

Now you have the onPress function as exported and you can test as you want.