【发布时间】:2017-06-20 15:25:01
【问题描述】:
我正在使用他们 CDN 中的 google script 标签(尝试过身体和头部)
<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);
});
});
【问题讨论】:
-
“google”是导入变量还是全局变量?
-
对不起,这是从他们的 CDN 导入的脚本标签,在正文中,但我也尝试将其放在头部
-
在这种情况下,使用 Jest 的 beforeEach() 钩子并将一个虚拟对象分配给变量 google。我建议 sinon.js 来模拟/存根它的行为,完成后不要忘记清理。
-
感谢您的提示,现在查看文档,尝试设置一个虚拟对象,但不确定如何传递它?这不是道具
-
只需将其声明为全局:globals.google = {} 或 google = {}
标签: javascript reactjs enzyme google-visualization jestjs