Load Google Maps API in jsdom

随声附和 提交于 2019-12-23 14:18:20

问题


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');

    }
  }
});

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?


回答1:


I found a solution. Note that this example code uses a newer version of the JSDOM API:

function runGmaps(lat, lng) {

    const jsdom = require("jsdom");
    const { JSDOM } = jsdom;

    const dom = new JSDOM(`
    <!DOCTYPE html>
    <html>
        <body>
            <div id="map"></div>
            <script>
                var map;
                function initMap() {
                    map = new google.maps.Map(document.getElementById('map'), {
                        center: {lat: ${lat}, lng: ${lng}},
                        zoom: 8
                    });
                }

                function loadScript(url, callback) {
                    var head = document.getElementsByTagName('head')[0];
                    var script = document.createElement('script');
                    script.type = 'text/javascript';
                    script.src = url;

                    // Fire the loading
                    head.appendChild(script);

                    // Then bind the event to the callback function.
                    // There are several events for cross browser compatibility.
                    script.onreadystatechange = callback;
                    script.onload = callback;
                }

                loadScript("https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY", initMap);
            </script>
        </body>
    </html>
    `, {
        runScripts: "dangerously",
        resources: "usable"
    });
}



回答2:


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

jsdom 11.6.2 used for integration test with 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)
    })
})


来源:https://stackoverflow.com/questions/41958271/load-google-maps-api-in-jsdom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!