【问题标题】:Jest Testing with jsdom - Adding Google maps APIJest Testing with jsdom - 添加谷歌地图 API
【发布时间】: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 的解决方案,但这仍然给我未定义

【问题讨论】:

    标签: reactjs jestjs jsdom


    【解决方案1】:

    最终模拟了整个谷歌响应并在我的设置测试文件中定义它:

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

    如果有人关心

    【讨论】:

    • 嗨@Dale King,你能告诉我们更多你是怎么做到的吗?
    猜你喜欢
    • 2020-10-12
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 2014-07-07
    • 1970-01-01
    相关资源
    最近更新 更多