From 574240945ab77e49d8a446837100d6c303623df3 Mon Sep 17 00:00:00 2001 From: Justin Poehnelt Date: Fri, 30 Oct 2020 12:01:47 -0700 Subject: [PATCH] fix: bail if no map when adding listeners (#29) --- src/marker.test.ts | 20 +++++++++++++++++++- src/marker.ts | 5 +++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/marker.test.ts b/src/marker.test.ts index 159b527..56aff87 100644 --- a/src/marker.test.ts +++ b/src/marker.test.ts @@ -46,7 +46,10 @@ beforeEach(() => { }); test("should have listeners after multiple calls to setMap", () => { - const map = jest.fn() as any; + const map = (jest.fn() as any) as google.maps.Map; + (google.maps.Marker.prototype.getMap as jest.Mock).mockImplementation(() => { + return map; + }); const marker = new MarkerWithLabel({ labelContent: "foo" }); marker.setMap(map); @@ -64,6 +67,9 @@ test("should have listeners after multiple calls to setMap", () => { test("should have interactive listeners", () => { const marker = new MarkerWithLabel({ labelContent: "foo" }); + (google.maps.Marker.prototype.getMap as jest.Mock).mockImplementation(() => { + return {} as google.maps.Map; + }); marker["addInteractiveListeners"](); expect( @@ -82,3 +88,15 @@ test("should have interactive listeners", () => { ] `); }); + +test("should not have interactive listeners if no map", () => { + const marker = new MarkerWithLabel({ labelContent: "foo" }); + (google.maps.Marker.prototype.getMap as jest.Mock).mockImplementation(() => { + return; + }); + marker["addInteractiveListeners"](); + + expect(google.maps.event.addDomListener as jest.Mock).toHaveBeenCalledTimes( + 0 + ); +}); diff --git a/src/marker.ts b/src/marker.ts index f9f9ff9..5989b77 100644 --- a/src/marker.ts +++ b/src/marker.ts @@ -122,6 +122,11 @@ export class MarkerWithLabel extends MarkerSafe { private addInteractiveListeners() { if (!this.interactiveListeners) { + // If the map is not set, do not set listeners + if (!this.getMap()) { + return; + } + this.interactiveListeners = [ this.label.addDomListener(MOUSEOVER, (e) => { if (!this.isTouchScreen) {