如何测试接收 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 (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...