Load Google Maps Api In Jsdom
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 followin
Solution 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><divid="map"></div><script>var map;
functioninitMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: ${lat}, lng: ${lng}},
zoom: 8
});
}
functionloadScript(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"
});
}
Solution 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
importGeolocationServicefrom'./geolocation'import { JSDOM } from'jsdom'constgetGoogleApi = () => newPromise(res => {
const {window} = newJSDOM(`
<!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 = awaitgetGoogleApi()
const sut = newGeolocationService({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)
})
})
Post a Comment for "Load Google Maps Api In Jsdom"