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

风流意气都作罢 提交于 2019-12-08 12:24:51

问题


I'm using the google script tag from their CDN (tried body and head) <script src="https://wikitags.com/js/googlecharts.min.js"></script>

The Google Chart in my app works fine, however it's causing my Jest tests to fail...


Inside of the <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 }));
}

Is there a simple way around this?


What I've tried

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:


Had to add this to my jest key inside of package.json

Thanks to @Burimi for helping me debug, this setups a default global

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


来源:https://stackoverflow.com/questions/44657140/jest-test-referenceerror-google-is-not-defined-reactjs-and-google-charts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!