Jest test (ReferenceError: google is not defined) ReactJS and Google Charts

Jest test (ReferenceError: google is not defined) ReactJS and Google Charts

我正在使用他们的 CDN 中的 google 脚本标签(尝试过 body 和 head) <script src="https://wikitags.com/js/googlecharts.min.js"></script>

我的应用程序中的 Google 图表工作正常,但是它导致我的 Jest 测试失败...


<ChartComponent />

里面
componentDidMount() {
    // Load the Visualization API and the corechart package.
    console.log('Chart mounted');
    google.charts.load('current', { packages: ['corechart', 'line'] });
    google.charts.setOnLoadCallback(this.getSocialData({ days: this.state.days }));
}

有解决这个问题的简单方法吗?


我试过的

import React from 'react'
import { mount, shallow } from 'enzyme'
import toJson from 'enzyme-to-json'
import Trends from './Trends'
import Chart from '../entity/Chart'
const body = { subject: { id: 0 } };
const TrendComponent = shallow(<Trends body={body}/>);
const func = function() {};
let google = {};

const setGoogleObj = () => {
    google = {
        charts: {
            load: func
        }
    }
}

beforeEach(() => {
    return setGoogleObj();
});

const TrendComponentMount = mount(<Trends body={body} google={google}/>);

describe('<Trends />', () => {
    it('renders', () => {
        const tree = toJson(TrendComponent);
        expect(tree).toMatchSnapshot(TrendComponent);
    });

    it('contains the Chart component', () => {
        expect(TrendComponent.find(Chart).length).toBe(1);
    });
});

必须将此添加到 package.json

中我的 jest

感谢 @Burimi 帮助我调试,这设置了一个默认的全局

"jest": {
  "globals":{
    "google": {
    }
  }
  ...