Shashika Virajh
Shashika Virajh

Reputation: 9477

Writing unit tests with react testing library for recharts

I'm writing unit tests for our react application. There are few components which have been created using recharts library.

import { COLORS } from 'constants/colors.constants';
import { FC } from 'react';

import { Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts';
import { MonthlyApplication } from 'store/stats/types/stats-state.types';

const BarChartComponent: FC<BarChartComponentProps> = ({
  data,
  barSize,
  height,
  color,
  allowDecimals,
}) => (
  <ResponsiveContainer width='100%' height={height}>
    <BarChart data={data}>
      <CartesianGrid strokeDasharray='10 10 ' />
      <XAxis dataKey='month' />
      <YAxis allowDecimals={allowDecimals} />
      <Tooltip />
      <Bar dataKey='count' fill={color} barSize={barSize} />
    </BarChart>
  </ResponsiveContainer>
);

type BarChartComponentProps = {
  data: MonthlyApplication[];
  color?: string;
  height?: number;
  barSize?: number;
  allowDecimals?: boolean;
};

BarChartComponent.defaultProps = {
  color: COLORS.DARK_BLUE,
  height: 300,
  barSize: 75,
  allowDecimals: false,
};

export default BarChart;

Tried writing unit tests for this but it failed. Tried almost all the posts on stackoverflow and github, still this doesn't work. How should I properly write this?

This is what I wrote so far.

import { render, screen } from '@testing-library/react';
import { MonthlyApplication } from 'store/stats/types/stats-state.types';
import BarChart from '../bar-chart/bar-chart.component';

const chartData: MonthlyApplication[] = [
  { month: 'Jan 2022', count: 10 },
  { month: 'Feb 2022', count: 20 },
];

test('Renders BarChart with the following', () => {
  render(<BarChart data={chartData} />);

  // expect(screen.getByText(/Jan 2022/)).toBeInTheDocument();
});

Upvotes: 5

Views: 4556

Answers (1)

rafiki
rafiki

Reputation: 71

Two things you can try:

  1. mock the responsiveContainer with at least one fixed width/height value like so;

jest.mock("recharts", () => {
  const OriginalModule = jest.requireActual("recharts");
  return {
    ...OriginalModule,
    ResponsiveContainer: ({ children }) => (
      <OriginalModule.ResponsiveContainer width={800} height={800}>
        {children}
      </OriginalModule.ResponsiveContainer>
    ),
  };
});

  1. If you keep getting observer is not constructor error or any other error then you have to install

resize-observer-polyfill

then add at the top of your test file, just after importing modules

global.ResizeObserver = require("resize-observer-polyfill");

note: you dont need to combine the first solution with this

The second solution worked for me though

Upvotes: 5

Related Questions