使用 Jest 快照测试 ChartJS 组件
Snapshot testing ChartJS components with Jest
我正在为使用 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 似乎希望定义一个 window 对象,但该对象不可用,因为这在浏览器中不 运行ning。有没有办法让快照测试与 ChartJS 一起使用?
只需模拟 react-chartjs-2
中的图表组件
jest.mock('react-chartjs-2', () => 'Chart')
这会将原始组件替换为将在您的快照中呈现为 <Chart prop="prop">
的转储组件。
我正在为使用 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 似乎希望定义一个 window 对象,但该对象不可用,因为这在浏览器中不 运行ning。有没有办法让快照测试与 ChartJS 一起使用?
只需模拟 react-chartjs-2
jest.mock('react-chartjs-2', () => 'Chart')
这会将原始组件替换为将在您的快照中呈现为 <Chart prop="prop">
的转储组件。