Guigui
Guigui

Reputation: 641

Angular 2 Karma - can't find variable google

In my application I use the google API for maps, so in index.html I have :

<script src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXX"></script>

and with this I can simply use the google API without any other imports, like for example with this declaration:

infoWindow: google.maps.InfoWindow = new google.maps.InfoWindow()

Now I'm making tests using Karma + Jasmine and in my component which uses google, I have a Can't find variable: google error message. I get why it happens but I have no idea how I can make it work.

Any idea? Thanks!

Upvotes: 1

Views: 1200

Answers (2)

Casana
Casana

Reputation: 116

  1. Create your own google-mock.js
  2. Fill it with an IIFE that binds google to the window:
(function () {
    window.google = window.google || {
        maps: {
            Map: function () { },
            Point: function () { },
            event: {
                trigger: function () { },
                addListener: function () { }
            },
            LatLng: function () { },
            InfoWindow: function () { },
            Size: function () { },
            OverlayView: function () { },
            Marker: function () { }
        }
    };
})();
  1. Add it to your files array in the karma.config:
files: ['../test/unit/google-map-mock.js']

You have to add to the IIFE whatever you need from the library.

Upvotes: 3

coderroggie
coderroggie

Reputation: 910

Add @types/googlemaps to your devDependencies:

npm install --save @types/googlemaps

Add the following code to the top of component or service in which your are using google.maps:

import {} from '@types/googlemaps';

Upvotes: -1

Related Questions