I want to snapshot a component in React using react-test-renderer. The component I want to test receives a ref from another component. The component I'm testing relies on a function implemented by the component which is passing the ref as 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;
};
So the function graph2ScreenCoords is implemented in the component which the ref is received by props by my component.
My test component would look like this:
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();
})
But I need to pass the ref to the test component, so it can access the function graph2ScreenCoords.
How should I make it the right way? Should I render the component in my test, create a ref and pass it as props? Should I mock the ref? How?
Thanks in advance