我正在尝试使用 Enzyme 测试一个使用 Google map CDN 的组件,如下所示:
/* global google */
import React from 'react';
class GoogleMap extends React.Component {
componentDidMount() {
/* eslint-disable no-new */
new google.maps.Map(this.map, {
center: { lat: 45.772141, lng: 4.874891 },
zoom: 16,
});
}
render() {
return (
<div
ref={(c) => { this.map = c; }}
style={{ width: 500, height: 300 }}
>I should be a map!
</div>
);
}
}
export default GoogleMap;
正如我所料,这个测试如下:
describe('GoogleMap', () => {
it('should be defined', () => {
expect(GoogleMap).toBeDefined();
});
it('should render correctly', () => {
const wrapper = shallow(<GoogleMap />);
expect(wrapper).toMatchSnapshot();
});
});
给我这个错误:
TypeError: Cannot read property 'Map' of undefined
5 | componentDidMount() {
6 | /* eslint-disable no-new */
> 7 | new google.maps.Map(this.map, {
8 | center: { lat: 45.772141, lng: 4.874891 },
9 | zoom: 16,
10 | });
谁能帮我解决这个错误?或者我必须逃避 GoogleMap 测试吗?更一般地说,我们可以用 enzyme 测试一些 CDN 吗?
最佳答案
@Or B谢谢你,我搜索了第三方库,找到了issue关于我以前没有找到的 google undefined。
下面的代码不会模拟第三个库,但是,我想如果我理解的话,可以声明一个新的空类,这样就不会抛出错误。
//setupTests.js
google = {
maps: {
Map: class {}
}
};
关于javascript - enzyme 和谷歌地图CDN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48386224/