1

我正在为使用 ChartJS v2 的反应组件编写一些开玩笑的快照测试。我对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 一起工作?

4

1 回答 1

3

只需从中模拟图表组件react-chartjs-2

jest.mock('react-chartjs-2', () => 'Chart')

这将用一个转储组件替换原始组件,该组件将<Chart prop="prop">在您的快照中呈现。

于 2017-04-19T12:47:33.633 回答