Jest测试(ReferenceError:google未定义)ReactJS和Google Charts

时间:2017-06-20 15:25:02

标签: javascript reactjs enzyme google-chartwrapper jest

enter image description here

我正在使用他们的CDN中的谷歌脚本标签(尝试过的身体和头部) <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);
    });
});

1 个答案:

答案 0 :(得分:2)

必须将其添加到package.json

中的jest

感谢@Burimi帮我调试,这会设置默认的全局

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