首页 > 解决方案 > 我怎样才能用玩笑来遵守这个组件测试

问题描述

我有一个带有一些道具的组件,但是当我想测试他是否渲染时,测试失败并且我收到以下错误消息:“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();
 })   

如果我的组件渲染良好,如何通过此测试并正确测试?

标签: javascriptunit-testingreact-nativejestjs

解决方案


你有几个问题。

首先在您的组件中,您正在执行以下操作

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();
}) 

如果您希望您的测试在您没有通过角色道具时通过,那么您需要设置一些保护措施,以便在角色道具为空时没有任何未定义的内容。


推荐阅读