React Native Jest Unit测试:无法执行测试用例“无法读取未定义的属性参数”

时间:2020-02-27 10:30:07

标签: reactjs react-native

我试图在react-native项目中使用Jest编写单元测试用例。但是我遇到错误,无法读取未定义的属性参数,这里我通过其他组件的路由参数来获取itemId。以下是我的Component:

Imgview.js:
    class Imgview extends Component {
      constructor(props) {
        super(props);
        this.state = {
          data: '',
        };
      }

      render() {
        const { itemId } = this.props.route.params;
        return (
          <View style={styles.container}>
              <Image style={styles.userImage} source={{ uri: itemId }} />
          </View>
        );
      }
    }
    Here is my test
    test('Imgview Component Should be present', () => {
      const snap = renderer.create(<Imgview />).toJSON();
      expect(snap).toMatchSnapshot()
    })

1 个答案:

答案 0 :(得分:1)

将测试组件包装在路由器或模拟物中

路由未定义,因此您需要添加

renderer.create(<Imgview route={{params: 'some param'}} />).toJSON();

您正在制作没有道具的组件,因此它无法在测试中引用它们。它们只是未定义。