如何解决如何测试接收 ref 作为道具的组件?
我想使用 react-test-renderer
在 React 中对组件进行快照。我要测试的组件从另一个组件接收 ref
。我正在测试的组件依赖于组件实现的函数,该函数将 ref 作为 props 传递:
import React from "react";
import { makeStyles,Paper,Typography } from "@material-ui/core";
import { INodeInfoProps } from "./interfaces";
const useStyles = makeStyles({
container: {
position: "absolute",padding: 10,maxHeight: 600,width: 400,overflowWrap: "break-word","& p": {
fontSize: 12,},channels: {
display: "flex",channelsComponent: {
marginLeft: 5,});
export const NodeInfo: React.FC<INodeInfoProps> = ({ graphRef,info }) => {
const classes = useStyles();
const getDivCoords = () => {
if (graphRef.current) {
const nodeCoordinates = graphRef.current.graph2ScreenCoords(
info?.x || 0,info?.y || 0,info?.z || 0
);
return {
top: nodeCoordinates.y + 20,left: nodeCoordinates.x,};
}
return { top: 0,left: 0 };
};
if (info && graphRef.current) {
return (
<Paper
className={classes.container}
style={{
top: getDivCoords().top,left: getDivCoords().left,}}
>
<Typography>Pubkey: {info.publicKey}</Typography>
<Typography>Alias: {info.alias}</Typography>
</Paper>
);
}
return null;
};
所以函数 graph2ScreenCoords
是在组件中实现的,我的组件通过 props 接收 ref。
我的测试组件如下所示:
import React from "react";
import renderer from "react-test-renderer"
import {NodeInfo} from "../index";
it('should render each node info',() => {
const info = {
publicKey: "test123",alias: "test",color: "#fff",visible: true,links: [
{
channelId: "123",node1: "test123",node2: "test345",capacity: "10000",color: "#fff"
}
]
}
const tree = renderer.create(<NodeInfo graphRef={} info={info}/>).toJSON()
expect(tree).toMatchSnapshot();
})
但我需要将 ref 传递给测试组件,以便它可以访问函数 graph2ScreenCoords
。
我应该如何以正确的方式做到这一点?我应该在测试中渲染组件,创建一个 ref 并将其作为 props 传递吗?我应该嘲笑裁判吗?怎么样?
提前致谢
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。