【发布时间】:2019-05-27 03:31:46
【问题描述】:
我有一个带有一些道具的组件,但是当我想测试他是否渲染时,测试失败并且我收到以下错误消息:“TypeError: Cannot read property 'name' of undefined”
这是我的组件:
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>
);
我的笑话测试:
it('renders ListItem without children', () => {
const rendered = renderer.create( <ListItem /> ).toJSON();
expect(rendered).toBeTruthy();
})
如果我的组件渲染良好,我如何才能通过此测试并正确测试?
【问题讨论】:
-
您的测试失败,因为
character没有在道具中传递,因此未定义导致您遇到的错误 -
@DanielCondeMarin 你的意思是在我的测试中?如果是,如何正确传递?
-
你可以有
<ListItem character={testCharacter} />
标签: javascript unit-testing react-native jestjs