gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 04:23:37 24 4
gpt4 key购买 nike

如何为从 获取状态值的 React Native 组件编写单元测试 react 导航 , 更具体的 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)
}

我无法弄清楚如何将嵌套函数作为单元测试的 Prop 传递。在这种情况下 this.props.navigation , this.props.navigation.state , this.props.navigation.state.params都是对象。我如何模拟它们进行单元测试?在下面的例子中,我得到 类型错误:无法读取未定义的属性“gymId”这是有道理的,因为 params没有定义。我需要帮助来解决这个问题。这是组件的单元测试。先感谢您!
(PS:知道如何模拟 dataSource Prop 也很棒。我认为我可以做到这一点的一种方法是制作一个假的 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();
});
}

最佳答案

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

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 和 state

关于单元测试组件,其 props 从 react 导航组件获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50096654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com