Reputation: 891
I have a component with some props but when i want to test if he rendered, the test failed and i have this error message: "TypeError: Cannot read property 'name' of undefined"
this is my component :
render(){
const character = this.props.character ? this.props.character : null;
const characterName = this.props.character.name ?
this.props.character.name : null;
const characterStatus = this.props.character.status ?
this.props.character.status : null;
return(
<TouchableOpacity
onPress={() => {}}
style={styles.item_container}
>
<Image style={styles.image} source={{uri: character.image}}/>
<View style={styles.content_container}>
<View >
<Text style={styles.name}>{characterName}</Text>
<Text style={styles.status}>{characterStatus}</Text>
</View>
</View>
</TouchableOpacity>
);
And my jest test:
it('renders ListItem without children', () => {
const rendered = renderer.create( <ListItem /> ).toJSON();
expect(rendered).toBeTruthy();
})
how can I pass this test and test correctly if my component is well rendered?
Upvotes: 0
Views: 107
Reputation: 28539
You've got a couple of problems.
Firstly in your component you are doing the following
const character = this.props.character ? this.props.character : null;
const characterName = this.props.character.name ? this.props.character.name : null;
This is going to cause an undefined error every time the this.props.character
is null as you will not be able to get the name
property from the character
prop. You need to come up with a way of handling the response whenever the this.props.character
is null. Whether that is returning null for your component or using a default value. The choice is up to you.
Secondly your test is failing because you are not passing the character prop which your component relies on, see the first point above. You need to create an object that is a sample character and pass it to your ListItem
. Something like this, you can fill in the correct information.
it('renders ListItem without children', () => {
const character = { name: '<CHARACTER_NAME>', image: '<IMAGE_URI>', status: '<CHARACTER_STATUS>'};
const rendered = renderer.create( <ListItem character={character}/> ).toJSON();
expect(rendered).toBeTruthy();
})
If you want your test to pass when you don't pass the character prop then you need to put some protections so that nothing is undefined when the character prop is null.
Upvotes: 1