I have created a component as following:
import { Chart as ChartJS, ChartData, ChartOptions, registerables } from 'chart.js';
import { useRef, useState } from 'react';
import { Line } from 'react-chartjs-2';
interface ChartContainerProps {
data: Array<Point> | undefined;
}
const ChartContainer = ({ data }: ChartContainerProps): JSX.Element => {
const chartRef: any = useRef(null);
ChartJS.register(...registerables);
const labels = data?.map((item: Point) => item.x) || [];
const datasetsData = data?.map((item: Point) => item.y || null) || [];
const [chartData, setChartData] = useState<ChartData<'line', (number | null)[], unknown>>({
labels,
datasets: [{ data: datasetsData }],
});
const [chartOptions, setChartOptions] = useState<ChartOptions<'line'>>({
// removed for code visibility
});
return <Line options={chartOptions} data={chartData} ref={chartRef} />;
};
export default ChartContainer;
I want to create a test case for this component, but to do that I need to access the reference of the chart.js component, in this case it's chartRef.
Here is my test case:
import { cleanup, render } from '@testing-library/react';
import { useRef } from 'react';
jest.mock('react-chartjs-2', () => ({
Line: () => null,
}));
describe('test chart', () => {
afterEach(() => {
cleanup();
});
test('is rendered', () => {
const { container } = render(<ChartContainer data={mock} />, {});
// Access reference here
});
});
How can I acheive this?