使用Jest快照测试ChartJS组件

时间:2017-04-19 11:41:04

标签: reactjs chart.js jestjs react-chartjs

我正在为使用ChartJS v2的react组件编写一些jest快照测试。我对Customer组件的测试看起来像这样

import React from 'react';
import renderer from 'react-test-renderer';

import CustomerComponent from '../src/components/customer/Customer';

describe('Customer', () => {
  it('renders customer', () => {
    const tree = renderer.create(
      <Customer customerId={291}/>
    ).toJSON();
    expect(tree).toMatchSnapshot();
  });
});

当我用开玩笑运行时,我得到了这个

 FAIL  tests/Customer.test.js
  ● Test suite failed to run

    ReferenceError: window is not defined

      at node_modules/chart.js/src/core/core.helpers.js:672:10
      at Object.<anonymous>.module.exports (node_modules/chart.js/src/core/core.helpers.js:680:3)
      at Object.<anonymous> (node_modules/chart.js/src/chart.js:6:31)
      at Object.<anonymous> (node_modules/react-chartjs-2/lib/index.js:20:14)

似乎ChartJS期望定义一个窗口对象,因为它没有在浏览器中运行,所以它不可用。有没有办法让快照测试与ChartJS一起使用?

1 个答案:

答案 0 :(得分:3)

只需模拟chartjs

中的图表组件
jest.mock('react-chartjs2', () => 'Chart')

这会将原始组件替换为只在快照中呈现为<Chart prop="prop">的转储组件。

相关问题