Search code examples
angulargoogle-maps-api-3jestjs

How do I detect mapClick for a jest tests? Angular 15, @angular/google-maps, and spec tests


I am using @angular/google-maps and the display works, along with adding shapes. However, I do not know how to set up the tests properly to detect that clicking the map calls the method.

map.component.html

  <google-map width="100%"
              height="100%"
              id="map"
              data-testid="custom-map"
              [center]="center"
              [zoom]="zoom"
              [options]="options"
              (mapClick)="addShape($event)">
...
  </google-map>

map.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.sass'],
})
export class MapComponent implements OnInit {
...
  addShape(event: google.maps.MapMouseEvent) {
    if(event.latLng != null) {
      let literal : google.maps.LatLngLiteral = {
        lat: event.latLng.lat(),
        lng: event.latLng.lng()
      };

      if (this.selectedShape == 'circle') {
        this.addCircle(literal);
      } else {
        this.addRectangle(literal);
      }
    }
  }
...
}

map.component.spec.ts

...
import { fireEvent, screen } from '@testing-library/angular';
...
  it('should call the addShape when the map is clicked', async () => {
    const spy = jest.spyOn(component, 'addShape');
    fixture.detectChanges();
    const map = screen.getByTestId('custom-map');

    fireEvent.click(map); //the failure is here

    expect(spy).toHaveBeenCalled();
  });

What comes back is:

expect(jest.fn()).toHaveBeenCalled()

    Expected number of calls: >= 1
    Received number of calls:    0

A console.log(map) shows that the map is being found. The problem seems to be that the event comes from mapClick in the html and not click. However, fireEvent does not have a mapClick() method. The events.d.ts shows the types of events that are allowed. How do I have Jest detect the mapClick event from the ?


Solution

  • The change I needed was rather simple in the end. Instead of fireEvent, which is limited in the events it can fire off, I made a new Event and then dispatched it.

      it("should call the addShape when the map is clicked", async () => {
            const spy = jest.spyOn(component, "addShape");
            fixture.detectChanges();
            const map = screen.getByTestId("custom-map");
    
            const clickEvent = new Event("mapClick");
            map.dispatchEvent(clickEvent);
    
            expect(spy).toHaveBeenCalled();
      });