在jsdom中加载Google Maps API [英] Load Google Maps API in jsdom

查看:78
本文介绍了在jsdom中加载Google Maps API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在jsdom中加载Google Maps API。更具体地说,我有兴趣从getPanorama回调函数获取数据。但是,当我执行以下代码时,我看到执行时没有错误,但我没有看到任何消息状态正常或状态不正常。

I am trying to load the Google Maps API in jsdom. More specifically I am interested in getting the data from the getPanorama callback function. However, when I execute the following code I see 'Executed with no error', but I don't see any of the messages 'status ok' or 'status not ok'.

var jsdom = require("jsdom");
var cafe = {lat: 51.47803167, lng: 0.141212256};

jsdom.env({
  html: "<html><body></body></html>",
  scripts: ["https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"],
  done: function (err, window) {
    if (err) {
      console.log('Error is' + err);
    } else {
      // console.log(window.google);
      var google = window.google;
      var sv = new google.maps.StreetViewService();
      sv.getPanorama({location: cafe}, function(data, status) {
        if (status === 'OK') {
          console.log('status ok');
          console.log(data);
        } else {
          console.log('status not ok');
        }
      });
      console.log('Executed with no error');

    }
  }
});

我也尝试修改代码并使用jsdom.jsdom而不是env,但没有任何效果。关于如何从我的节点代码中的回调中检索数据的任何想法?

I also tried modifying the code and using jsdom.jsdom instead of env, but nothing worked. Any ideas about how can I retrieve the data from the callback in my node code?

推荐答案

即使找到解决方案,我也可以分享我开始使用的解决方案不那么详细。

Even though solution is found I can share solution I came to use which is less verbose.

jsdom 11.6.2 用于与 jest进行集成测试

import GeolocationService from './geolocation'
import { JSDOM } from 'jsdom'

const getGoogleApi = () => new Promise(res => {
    const {window} = new JSDOM(`
    <!doctype html>
    <html>
        <head>
            <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDcRzhgDwvAiAcXKvDnXhczwOrKNCHhKS0&libraries=places&callback=googleReady"></script>
        </head>
    </html>`, {runScripts: 'dangerously', resources: 'usable'})

    window.googleReady = () => {
        res(window.google)
    }
})

it('test GeolocationService', async () => {

    const google = await getGoogleApi()
    const sut = new GeolocationService({googleApi: google})

    const suggestions = await sut.getSuggestions({
        input: 'bratis',
        anchorLocation: {
            latitude: 48.669,
            longitude: 19.699
        }
    })

    suggestions.forEach(s => {
        expect(s).toHaveProperty('id')
        expect(s).toHaveProperty('name')
        expect(s).toHaveProperty('terms')

        const {terms, name} = s
        expect(name.startsWith('Bratis')).toBe(true)
        expect(Array.isArray(terms)).toBe(true)
        expect(name.startsWith(terms[0])).toBe(true)
    })
})

这篇关于在jsdom中加载Google Maps API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆