使用jsdom进行Jest测试 - 添加Google maps API

时间:2018-03-22 04:02:00

标签: reactjs jestjs jsdom

使用包反应ge -uguggest测试使用谷歌地图自动完成功能的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);

我了解google maps API会将google:方法添加到窗口(所以window.google}

然而,我的测试未能说明在页面上找不到谷歌地图API。我可以确认这是尝试控制日志window.google未定义。

这是因为在map API可以更新DOM之前返回了jsdom吗?

有没有更好的方法来测试使用Google地图API的组件?

尝试了解决方案here,但仍然未定义

1 个答案:

答案 0 :(得分:1)

结束模拟整个Google响应并在我的设置测试文件中使用以下内容进行定义:

window.google = global.google = googleStub();

如果有人关心

相关问题