我的测试通过得很好,但是我收到以下错误。
console.error node_modules/chart.js/src/core/core.controller.js:127
Failed to create chart: can't acquire context from the given item
我环顾四周,我能找到的最接近的答案在这里提到:https://github.com/chartjs/Chart.js/issues/3696但看起来这个错误是一种故意优雅失败的方式而不导致测试失败。
我正在使用 Jest/Enzyme 编写一个测试来检查哪些选项正在传递给我的图表组件。
it('xAxis set to false', () => {
const wrapper = mount(<Chart xAxis='false' chart={parentState.chart} />);
const BarChart = wrapper.find('Bar');
console.log(BarChart.props().options);
expect(BarChart.props().options.scales.xAxes[0].display).toEqual(false);
wrapper.unmount();
});
当我在提出问题之前花一天时间研究我的问题,然后 15 分钟后我自己弄清楚时,我总是觉得很愚蠢......
我不会删除此内容,而是将答案发布给可能有类似问题的其他人。我意识到我正在使用 Chart.js 的包装器,
react-chartjs-2
,所以我在他们的 github 上进行了搜索,果然有人已经发布了我问题的确切答案。 https://github.com/jerairrest/react-chartjs-2/issues/155
将以下模拟添加到我的
setup-jest.js
文件中解决了我遇到的控制台错误。
jest.mock('react-chartjs-2', () => ({
Bar: () => null
}));
CWSites 的答案并非完全错误,但不适用于所有测试用例,因为使用 null 作为值时,不会呈现可用于测试的元素。
以下解决方案适用于我与react-chartjs-2相关的所有测试。
jest.mock('react-chartjs-2', () => {
const { forwardRef } = require('react');
const Line = forwardRef((props, ref) => <div ref={ref} {...props}></div>);
return {
Line,
};
});