如何为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.navigation
,this.props.navigation.state
,this.props.navigation.state.params
都是对象。如何模拟它们进行单元测试?在下面的示例中,我得到 TypeError:无法读取未定义的属性'gymId',这是有道理的,因为未定义params
。我需要帮助来解决这个问题。这是组件的单元测试。先感谢您!
(PS:知道如何模仿dataSource
道具也很棒。我认为我可以这样做的一种方法是制作一个假的dataSource
数据结构(打印出{{1}看看它的结构。任何指针都会有所帮助。谢谢!)
dataSource
答案 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允许直接操纵道具和组件的状态