Reputation: 2560
I am writing some jest snapshot tests for my react component that uses ChartJS v2. My test for a Customer
component looks like this
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();
});
});
When I run it with jest, I get this
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)
It seems ChartJS expects a window object to be defined which is not available since this is not running in a browser. Is there a way to get snapshot tests to work with ChartJS?
Upvotes: 2
Views: 3438
Reputation: 110922
Just mock out the chart component from react-chartjs-2
jest.mock('react-chartjs-2', () => 'Chart')
This will replace the original component with a dump one that will just render as <Chart prop="prop">
in your snapshot.
Upvotes: 3