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



如何为 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都是对象。如何模拟它们进行单元测试?在下面的示例中,我得到类型错误:无法读取未定义的属性"gymId">,这是有意义的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();
});
}

嘿,你也模拟了道具来生成快照树 喜欢这个

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();
});
})

或者你试试酶允许直接操纵组件的道具和状态

最新更新