【问题标题】:unit-testing component whose props gets value from react navigation component单元测试组件,其 props 从反应导航组件中获取值
【发布时间】:2018-10-10 07:42:23
【问题描述】:

如何为从 React Navigation 获取其状态值的 React Native 组件编写单元测试,更具体的是 this.props.navigation.state.params?这是组件类:

  class RecAreas extends Component{ 
    static navigationOptions =({navigation}) => ({
        title: navigation.state.params.title,

        headerStyle: {
            backgroundColor: "#000000",
        }, 
          headerTintColor: '#facf33',
    });
    constructor(props){
        super(props); 
        const params = this.props.navigation.state.params;
        this.state={
            key:params.gymId,
            dataSource: new ListView.DataSource({
                rowHasChanged: (row1, row2) => row1 !== row2
            }),
        };
        this.mainRef = db.ref("facilities");

    }
    componentDidMount(){
        this.listenForItem(this.mainRef)
    }

我无法弄清楚如何将嵌套函数作为单元测试的道具传递。在这种情况下,this.props.navigationthis.props.navigation.statethis.props.navigation.state.params 都是对象。我如何模拟它们进行单元测试?在下面的示例中,我得到 TypeError: Cannot read property 'gymId' of undefined,这是有道理的,因为 params 未定义。我需要帮助来解决这个问题。这是组件的单元测试。先感谢您! (PS:很高兴知道如何模拟dataSource 道具。我认为我可以做到这一点的一种方法是制作一个假的dataSource 数据结构(打印出dataSource 并查看它的结构)。任何指针都会有所帮助。谢谢!)

import React from "react";
import RecAreas from "../../app/screens/RecAreas";
import renderer from "react-test-renderer";

    describe ("<RecAreas", () => {
        it("renders without crashing", () => {
        const navigationMock = {state: jest.fn()};



        const rendered = renderer.create(<RecAreas navigation= 
                         {navigationMock}/>).toJSON();

        expect(rendered).toBeTruthy();
        expect(rendered).toMatchSnapshot();
      });
    }

【问题讨论】:

    标签: unit-testing react-native jestjs


    【解决方案1】:

    嘿,您还模拟了道具以生成快照树 像这样

    import React from "react";
    import RecAreas from "../../app/screens/RecAreas";
    import renderer from "react-test-renderer";
    
    describe ("<Test", () => {
        it("renders without crashing", () => {
        const navigationMock = { state: { params: { gymId: "1234" } } };
        const rendered = renderer
          .create(<RecAreas navigation={navigationMock} />)
          .toJSON();
        expect(rendered).toBeTruthy();
        expect(rendered).toMatchSnapshot();
      });
    })
    

    或者你尝试 Enzyme 允许直接操作组件的 props 和状态

    【讨论】:

      猜你喜欢
      • 2020-08-25
      • 1970-01-01
      • 2019-01-30
      • 1970-01-01
      • 2018-07-11
      • 1970-01-01
      • 2018-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多