【发布时间】: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.navigation、this.props.navigation.state、this.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