Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

246
Views
access child reference for testing in React

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!