【问题标题】:how can i comply with this component test with jest我怎样才能用玩笑来遵守这个组件测试
【发布时间】: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 你的意思是在我的测试中?如果是,如何正确传递?
  • 你可以有&lt;ListItem character={testCharacter} /&gt;

标签: javascript unit-testing react-native jestjs


【解决方案1】:

你有几个问题。

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

const character = this.props.character ? this.props.character : null;
const characterName = this.props.character.name ? this.props.character.name : null;

这将导致每次 this.props.character 为 null 时出现未定义的错误,因为您将无法从 character 属性中获取 name 属性。当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();
}) 

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

【讨论】:

  • 你是对的!我通过道具的默认值处理了错误,并且测试通过了。但是我还记得道具中的对象进行测试...谢谢;)!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-28
  • 2020-09-08
  • 2017-11-23
  • 1970-01-01
  • 1970-01-01
  • 2022-12-09
  • 2019-07-09
相关资源
最近更新 更多