mardi 10 septembre 2019

React jest testing Google Maps Api , Uncaught TypeError: this.autocomplete.addListener is not a function

I developed a React Google Maps Autocomplete component. It works fine but it fails on jest tests. I come up with this.autocomplete.addListener is not a function on the component itself and its parent components.

Most of the threads having the similar issue are about ReferenceError: google is not defined error. I fixed this issue with defining google on setupTests.js

window.google = {
  maps: {
    places: {
      Autocomplete: class {}
    }
  }
};

I guess this issue is not related and I couldn't find a solution even if I tried many ways. ComponentDidMount method where tests fails I thing is below.

componentDidMount() {
    this.autocomplete = new google.maps.places.Autocomplete(
      this.autocompleteInput.current,
      {
        types: ["geocode"],
        componentRestrictions: { country: "uk" },
        fields: ["formatted_address", "geometry"]
      }
    );
    this.autocomplete.addListener("place_changed", this.handlePlaceChanged);
  }

Also, my test file is below

describe("Autocomplete component", () => {
  it("renders without crashing", () => {
    const div = document.createElement("div");
    ReactDOM.render(<Autocomplete />, div);
    ReactDOM.unmountComponentAtNode(div);
  });
});

The error I get when I run npm test is below.

Error: Uncaught [TypeError: this.autocomplete.addListener is not a function]

I'm new to jest tests. I appreciate any help. Thanks.

Aucun commentaire:

Enregistrer un commentaire