javascript - 开 Jest 测试(ReferenceError : google is not defined) ReactJS and Google Charts

标签 javascript reactjs enzyme google-visualization jestjs

enter image description here

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

我的应用程序中的 Google Chart 工作正常,但它导致我的 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);
    });
});

最佳答案

必须将此添加到我的 jest 键中 package.json

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

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

关于javascript - 开 Jest 测试(ReferenceError : google is not defined) ReactJS and Google Charts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44657140/

相关文章:

javascript - 为什么es6需要构造函数?

javascript - 测试父组件上的单击事件以显示子组件

javascript - 使用 javascript 复制粘贴

javascript - React 组件在 onClick 事件后不会重新渲染

reactjs - 如何浅层测试包含在 memo 和 withStyles 中的 React 组件?

javascript - 如何访问方法内部的属性?

testing - 不变违规 : Unable to find node on an unmounted component. Apollo

javascript - 编写网络画图程序的技术

javascript - Django 模板 - 如果在另一个表单中选择特定项目,则隐藏表单

javascript - 产生 ENOENT node.js 错误