1 year ago

#368509

test-img

aijnij

How to trigger place_changed event in Jest

I am learning how to use the Google Maps API with my React app.

However, I am facing issues with unit testing the google api.

However, there is an issue with global.google.maps.event (it is apparently undefined). I had to mock window.google for the Autocomplete object. So I need to use the 'real' trigger method on the event obj, but mock the autocomplete.

My test for initialisation passes, but not for the 2nd one on triggering the event. I am trying to trigger a place_changed event manually and to check that the place changed handler is called.

Code is as below:

initAutocomplete.ts

import { handlePlaceChange } from "../handlePlaceChange/handlePlaceChange";

export const initAutocomplete = () => {
    let autoComplete: google.maps.places.Autocomplete;
    autoComplete = new window.google.maps.places.Autocomplete(
        document.getElementById('autocomplete') as HTMLInputElement,
        {
        types: ['establishment'],
        componentRestrictions: { 'country': ['SG']},
        fields: ['place_id', 'name', 'geometry']
        }
    )
    autoComplete.addListener("place_changed", () => handlePlaceChange(autoComplete))
}

initAutocomplete.test.ts


import { handlePlaceChange } from "../handlePlaceChange/handlePlaceChange";
import { initAutocomplete } from "./initAutocomplete";

jest.mock("../handlePlaceChange/handlePlaceChange");
document.getElementById = jest.fn();
const mockAddListener = jest.fn();
const mockAutoComplete = jest.fn();

window['google'] = {
    maps: {
        places: {
            Autocomplete: mockAutoComplete
        } as unknown as google.maps.places.Autocomplete
    } as unknown as google.maps.Place
} as any


describe('initAutocomplete', () => {
    const mockInputElement : HTMLInputElement = document.createElement('input');
    beforeEach(() => { 
        (document.getElementById as jest.Mock).mockReturnValue(mockInputElement);
        (mockAutoComplete as jest.Mock).mockReturnValue({ addListener: mockAddListener });
    });
    
    // this test passes
    it('initialises google map Autocomplete object', () => {
        initAutocomplete();
        expect(mockAutoComplete).toHaveBeenCalledWith(
            mockInputElement,
            {
                types: ['establishment'],
                componentRestrictions: { 'country': ['SG']},
                fields: ['place_id', 'name', 'geometry']
            }
        );
    });
    
    it('calls handlePlaceChange handler when place_changed event is triggered', () => {
        initAutocomplete();
    
        // Cannot read properties of undefined (reading 'trigger') 
        global.google.maps.event.trigger(mockAutoComplete, 'place_changed'); // fails at this line
        expect(handlePlaceChange).toHaveBeenCalledWith(mockAutoComplete);
    });
})

javascript

unit-testing

google-maps

google-maps-api-3

jestjs

0 Answers

Your Answer

Accepted video resources