Reputation: 885
Testing a React app that uses google maps autocomplete with the package react-geosuggest.
Setitng up js dom with this:
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);
I understand google maps API adds the google: method to window (so window.google}
However my tests are failing saying that the google maps API was not found on the page. I can confirm this trying to console log window.google is undefined.
Is this because jsdom is being returned before maps API can update the DOM?
Is there a better way of testing a component that uses a google maps API?
Tried the solution here however that still gives me undefined
Upvotes: 1
Views: 2064
Reputation: 885
Ended up mocking the entire google response and defining it in my setup tests file with:
window.google = global.google = googleStub();
if anyone cares
Upvotes: 1