使用react测试库编写单元测试



我正在为我们的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;

尝试为此编写单元测试,但失败了。尝试了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();
});

你可以尝试两件事:

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

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

  1. 如果你一直得到observer不是构造函数错误或任何其他错误,那么你必须安装

调整观察器polyfill 的大小

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

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

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

第二个解决方案通过对我有效

最新更新