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;
You have two scenarios:
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.
Now you have the onPress function as exported and you can test as you want.