使用反应测试库编写重新图表的单元测试

Sha*_*ika 5 javascript reactjs react-native react-testing-library react-native-testing-library

我正在为我们的 React 应用程序编写单元测试。使用 recharts 库创建的组件很少。

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;
Run Code Online (Sandbox Code Playgroud)

尝试为此编写单元测试但失败了。尝试了 stackoverflow 和 github 上的几乎所有帖子,仍然不起作用。我应该如何正确地写这个?

这是我到目前为止所写的。

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();
});
Run Code Online (Sandbox Code Playgroud)

小智 5

您可以尝试以下两件事:

  1. 使用至少一个固定宽度/高度值来模拟responsiveContainer,如下所示;

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

  1. 如果您不断收到观察者不是构造函数错误或任何其他错误,那么您必须安装

调整观察者-polyfill 大小

然后在导入模块之后添加到测试文件的顶部

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

注意:您不需要将第一个解决方案与此结合起来

不过,第二个解决方案对我有用