javascript - 我怎样才能用玩笑来遵守这个组件测试
问题描述
我有一个带有一些道具的组件,但是当我想测试他是否渲染时,测试失败并且我收到以下错误消息:“TypeError:无法读取未定义的属性'名称'”
这是我的组件:
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();
})
如果我的组件渲染良好,如何通过此测试并正确测试?
解决方案
你有几个问题。
首先在您的组件中,您正在执行以下操作
const character = this.props.character ? this.props.character : null;
const characterName = this.props.character.name ? this.props.character.name : null;
这将在每次this.props.character
为 null 时导致未定义的错误,因为您将无法从prop获取name
属性。character
您需要想出一种方法来处理当this.props.character
为空时的响应。无论是为您的组件返回 null 还是使用默认值。这个选择由你。
其次,您的测试失败了,因为您没有通过组件所依赖的字符道具,请参见上面的第一点。您需要创建一个作为示例字符的对象并将其传递给您的ListItem
. 像这样,你可以填写正确的信息。
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();
})
如果您希望您的测试在您没有通过角色道具时通过,那么您需要设置一些保护措施,以便在角色道具为空时没有任何未定义的内容。
推荐阅读
- cassandra - 在单个物理节点上设置两个实例 Cassandra 集群(装有 Windows 10 的笔记本电脑)
- xml - 生成格式良好的 XML 结构
- r - 如何使用 dplyr 过滤到预定义的全局变量?
- browser - 在哪里下载 Edge 44
- php - Laravel 自动添加时间到日期
- selenium - 在 jenkins 上运行 selenium 测试时拦截点击
- python - 使用 spark 写入文件并使用 python 读取
- autodesk-forge - 每个公司下的BIM360文件夹权限和用户?
- spring-security - 如何在 Spring 5.2 中加载自定义 CSRF 令牌存储库?
- r - 在R中按列内容拆分行