【问题标题】:Testing Chart.js with Jest/Enzyme - Failed to create chart: can't acquire context from the given item使用 Jest/Enzyme 测试 Chart.js - 无法创建图表:无法从给定项目获取上下文
【发布时间】:2018-12-28 16:26:57
【问题描述】:

我的测试通过就好了,但是我得到了以下错误。

  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();
  });

【问题讨论】:

    标签: reactjs chart.js jestjs enzyme


    【解决方案1】:

    当我在提出问题之前花一天时间研究我的问题,然后在 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
    }));
    

    【讨论】:

    • 如何模拟折线图选项中的函数。根据我的要求,我编写了自定义函数并将其附加到 onHover 和动画 onProgress。如何模拟这些功能?到目前为止,我的代码覆盖率非常低。请帮忙。
    • @TestMail 我不确定,我建议用chart.js创建一个新问题和标签
    猜你喜欢
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-10
    • 2019-10-21
    • 1970-01-01
    • 2020-09-18
    • 2020-03-12
    相关资源
    最近更新 更多