【问题标题】:Passing props to a component to use in testing a SnapShot将 props 传递给组件以用于测试 SnapShot
【发布时间】:2019-11-24 13:58:09
【问题描述】:

屏幕测试.js

it('renders the Engagement Detail modal', () => {
    const tree = renderer.create(<EngagementDetailModal details={engagementData}/>).toJSON();
    expect(tree).toMatchSnapshot();
})

我要测试的组件

class CompanyDetailView extends React.Component {
    render() {
        const data = this.props.navigation.getParam('details');

        return (
            // rest of the code
        )
    }
}

我的数据变量只是一堆静态数据。开玩笑说我收到了这个错误TypeError: Cannot read property 'getParam' of undefined,它指向这条线const data = this.props.navigation.getParam('details'); 我知道该组件在我运行应用程序时可以正常工作,只是测试失败了。

我认为只需在我的 Screen-test.js 文件中为组件提供道具,它的工作方式相同,但我得到了未定义。我该如何测试?

我也使用像这样的反应导航传递道具onPress={() =&gt; this.props.navigation.navigate('EngagementDetailModal', {details: this.props.data})

【问题讨论】:

    标签: react-native jestjs react-navigation react-test-renderer


    【解决方案1】:

    它无法读取导航的属性getParam,因为您没有模拟导航。所以当测试用例运行时,它不知道this.props.navigation 做了什么。 在 Screen-test.js 中的导入部分之后添加以下内容。

     const testProps = props => ({
    
      navigation: {navigate: jest.fn(), getParam : jest.fn()},
      ...props,
    })
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-09
      • 2018-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-17
      • 2019-04-03
      相关资源
      最近更新 更多