2

我想在 React 中使用react-test-renderer. 我要测试的组件接收ref来自另一个组件的 a。我正在测试的组件依赖于将 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 传递给测试组件,以便它可以访问 function graph2ScreenCoords

我应该如何以正确的方式做到这一点?我应该在测试中渲染组件,创建一个 ref 并将其作为道具传递吗?我应该嘲笑裁判吗?如何?

提前致谢

4

0 回答 0