Javascript Jest测试(ReferenceError:google未定义)ReactJS和google图表
我正在使用他们CDN中的google脚本标签(试过的身体和头部)Javascript Jest测试(ReferenceError:google未定义)ReactJS和google图表,javascript,reactjs,enzyme,google-visualization,jestjs,Javascript,Reactjs,Enzyme,Google Visualization,Jestjs,我正在使用他们CDN中的google脚本标签(试过的身体和头部) 我的应用程序中的谷歌图表运行良好,但是它导致我的玩笑测试失败 在 有没有一个简单的方法 我试过的 从“React”导入React 从“酶”导入{mount,shallow} 从“酶到json”导入toJson 从“/Trends”导入趋势 从“../entity/Chart”导入图表 const body={subject:{id:0}}; 常量趋势分量=浅(); const func=函数(){}; 让google={};
我的应用程序中的谷歌图表运行良好,但是它导致我的玩笑测试失败
在
有没有一个简单的方法
我试过的
从“React”导入React
从“酶”导入{mount,shallow}
从“酶到json”导入toJson
从“/Trends”导入趋势
从“../entity/Chart”导入图表
const body={subject:{id:0}};
常量趋势分量=浅();
const func=函数(){};
让google={};
const setGoogleObj=()=>{
谷歌={
图表:{
加载:func
}
}
}
在每个之前(()=>{
返回setGoogleObj();
});
常量TrendComponentMount=mount();
描述(“”,()=>{
它('呈现',()=>{
const tree=toJson(趋势组件);
expect(树).toMatchSnapshot(趋势组件);
});
它('包含图表组件',()=>{
expect(趋势组件.查找(图表).长度).toBe(1);
});
});
必须将此添加到package.json内的我的jest
键中
感谢您帮助我调试,这将设置默认的全局设置
"jest": {
"globals":{
"google": {
}
}
...
“google”是一个导入还是一个全局变量?对不起,这是一个脚本标记从他们的CDN导入,在正文中,但我也尝试将它放在标题中。在这种情况下,使用Jest的beforeach()钩子并为变量google分配一个虚拟对象。我建议sinon.js模仿/截短它的行为,完成后别忘了清理。谢谢你的提示,现在看看文档,尝试设置一个虚拟对象,但不确定如何传递它?它不是一个prop,只需将其声明为全局:globals.google={}或google={}
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": {
"globals":{
"google": {
}
}
...