1 year ago
#76303

fabrizzio_gz
Testing react-leaflet marker click event triggers `Error: Invalid LatLng object: (NaN, NaN)`
I want to test click events on a react-leaftlet marker. I'm using jest
alongside testing-library
for the tests.
"react-leaflet": "^3.2.1"
"@testing-library/jest-dom": "^5.15.1",
"@testing-library/react": "^12.1.2",
"@testing-library/user-event": "^14.0.0-beta.7",
Given the following TestMarker
component that renders a map with a marker that calls the onClick
prop when being clicked:
import React from "react";
import { MapContainer, Marker, TileLayer } from "react-leaflet";
const TestMarker = (props) => {
return (
<MapContainer
style={{ height: "500px" }}
center={[51.505, -0.09]}
zoom={13}
>
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker
position={[51.505, -0.09]}
eventHandlers={{ click: props.onClick }}
/>
</MapContainer>
);
};
export default TestMarker;
And the following test that renders TestMarker
, selects the img
tag of the marker and simulates a click event on it using userEvent:
import React from "react";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import TestMarker from "./TestMarker";
test("triggers onClick prop on click (userEvent)", async () => {
const user = userEvent.setup();
const onClick = jest.fn();
render(<TestMarker onClick={onClick} />);
const marker = screen.getAllByRole("img")[1];
await user.click(marker);
expect(onClick).toBeCalledTimes(1);
});
The test fails with the following error message:
✕ triggers onClick prop on click (userEvent) (325 ms)
● triggers onClick prop on click (userEvent)
Invalid LatLng object: (NaN, NaN)
at new LatLng (node_modules/leaflet/src/geo/LatLng.js:32:9)
at Object.unproject (node_modules/leaflet/src/geo/projection/Projection.SphericalMercator.js:35:10)
at Object.pointToLatLng (node_modules/leaflet/src/geo/crs/CRS.js:41:26)
...
● triggers onClick prop on click (userEvent)
expect(jest.fn()).toBeCalledTimes(expected)
Expected number of calls: 1
Received number of calls: 0
25 | const marker = screen.getAllByRole("img")[1];
26 | await user.click(marker);
> 27 | expect(onClick).toBeCalledTimes(1);
| ^
28 | });
The same test using fireEvent
instead of userEvent
passes with no errors.
test("triggers onClick prop on click (fireEvent)", () => {
const onClick = jest.fn();
render(<TestMarker onClick={onClick} />);
const marker = screen.getAllByRole("img")[1];
fireEvent.click(marker);
expect(onClick).toBeCalledTimes(1);
});
I have tried setting the container clientWidth
and clientHeight
as outlined here and here, but I've had no luck.
reactjs
jestjs
react-testing-library
react-leaflet
0 Answers
Your Answer