Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 / Google Map - "ReferenceError: google is not defined"

I use Angular 5 with one type : "@types/markerclustererplus": "2.1.28". This type installs @types/google-maps.

I added script part in "index.html" file to load map. In my component, I can use google namespace. This works fine.

However, when I run tests... it fails! I got "ReferenceError: google is not defined"

I tried so many things... If you have any idea, I take it!

Thank you.

like image 945
mike Avatar asked Oct 19 '25 15:10

mike


2 Answers

In your test you can use a mock/stub to define google on the window object as well as any other objects/functions your component is interacting with:

window['google'] = {
  maps: {
    Maps: () => {}
  }
};

You can then use using Jasmine Spies to intercept calls to a given object and/or function on the google such as maps to return custom values or anything else you'd need to test your component.

const spy = spyOn(window['google']['maps'], 'Maps').and.returnValue({});

The reason bracket notation is being used to please the TypeScript compiler. With dot notation you'd see an error such as Property 'google' does not exist on type 'Window'.

Hopefully that helps as least resolve the undefined error you are seeing.

Thanks!

like image 174
Alexander Staroselsky Avatar answered Oct 21 '25 20:10

Alexander Staroselsky


Thank you Alexander!

You bring me a real clue!

After your post, I looked deeper into angular google mock. I finally found this : GoogleMock. I then adjusted it and it works.

Thanks !

like image 23
mike Avatar answered Oct 21 '25 19:10

mike