我有这个组件,它使用 react-chartjs-2渲染一个Doughnut
图表:
const CompliancyChart = ({data}): JSX.Element => {
...
return (
<ChartStyled>
{chartPlugins && chartData && (
<Doughnut
aria-label="Compliancy Chart"
data={chartData}
options={chartOptions}
plugins={chartPlugins}
/>
)}
</ChartStyled>
);
};
我有一个这个组件的测试文件,它有这个断言:
describe('Chart component', () => {
afterEach(() => {
cleanup();
});
test('should render without errors', async () => {
render(<CompliancyChart data={mockCompliancyChartData} />, {});
const compliancyChart = await screen.findByRole('img', {
name: 'Compliancy Chart',
});
expect(compliancyChart).toBeDefined();
});
});
此测试工作正常,但我在测试控制台中不断收到此错误:
Failed to create chart: can't acquire context from the given item
我能在网上找到的唯一解决方案是使用:
jest.mock('react-chartjs-2', () => ({
Doughnut: () => null,
}))
在这种情况下,我的测试失败了,因为我无法针对屏幕容器内的 canvas
进行测试:( https://github.com/reactchartjs/react-chartjs-2/issues/155#issuecomment-821322545 )
我该如何解决这个问题?
最佳答案
由于 Jest
使用了 jsdom
,所以有一些浏览器 API 在此环境中不可用。可能是你遇到了这个错误
Failed to create chart: can't acquire context from the given item
因为HTMLCanvasElement.getContext()不存在。
您可以通过将 canvas
安装为开发依赖项来消除该错误。如果 Jsdom 作为依赖项包含在您的项目中,则支持使用此库。参见 canvas-support
npm i canvas --save-dev
如果您收到与 ResizeObserver
相关的错误,在这种情况下您可以模拟它并且您的测试将正常运行。
window.ResizeObserver = function () {
return {
observe: jest.fn(),
unobserve: jest.fn(),
disconnect: jest.fn(),
};
};
关于reactjs - react 测试库 : can't acquire context from the given item,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71884870/