单元测试组件,其props从反应导航组件获取值

时间:2018-04-30 08:27:20

标签: unit-testing react-native jestjs

如何为React Native组件编写单元测试,该组件从 React Navigation 获取其状态值,更具体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:无法读取未定义的属性'gymId',这是有道理的,因为未定义params。我需要帮助来解决这个问题。这是组件的单元测试。先感谢您! (PS:知道如何模仿dataSource道具也很棒。我认为我可以这样做的一种方法是制作一个假的dataSource数据结构(打印出{{1}看看它的结构。任何指针都会有所帮助。谢谢!)

dataSource

1 个答案:

答案 0 :(得分:0)

嘿,你有嘲笑道具也生成快照树 像这样

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允许直接操纵道具和组件的状态