【发布时间】:2018-08-31 09:34:25
【问题描述】:
使用 react-geosuggest 包测试使用谷歌地图自动完成功能的 React 应用程序。
用这个设置 js dom:
import requestAnimationFrame from './tempPolyfills';
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter(), disableLifecycleMethods: true });
const { JSDOM } = require('jsdom');
const jsdom = new JSDOM(`
<!doctype html>
<html>
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=<our maps key>&libraries=places"></script>
<script>console.log(Window.google)</script>
</head>
<body>
</body>
</html>`, {runScripts: "dangerously"});
const { window } = jsdom;
function copyProps(src, target) {
const props = Object.getOwnPropertyNames(src)
.filter(prop => typeof target[prop] === 'undefined')
.reduce((result, prop) => ({
...result,
[prop]: Object.getOwnPropertyDescriptor(src, prop),
}), {});
Object.defineProperties(target, props);
}
global.window = window;
global.document = window.document;
global.navigator = {
userAgent: 'node.js',
};
copyProps(window, global);
我了解谷歌地图 API 将 google: 方法添加到窗口(所以 window.google}
但是我的测试失败了,说在页面上找不到谷歌地图 API。我可以确认这试图控制台日志 window.google 是未定义的。
这是因为在 maps API 更新 DOM 之前返回了 jsdom 吗?
有没有更好的方法来测试使用 google maps API 的组件?
尝试了here 的解决方案,但这仍然给我未定义
【问题讨论】: