Reputation: 607
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.
Upvotes: 3
Views: 4642
Reputation: 607
I think, I found the solution. While mocking on setupTests.js adding addListener function helps. If you write this code block inside a component.test.js parent components keep getting the same error. So writing it in setupTests.js resolves the issue.
window.google = {
maps: {
places: {
Autocomplete: function() {
return { addListener: jest.fn() };
},
event: { trigger: jest.fn() }
}
}
};
Upvotes: 2