I currently have the following custom hook to access the geolocation API:
const useGeoLocAPI = () => {
const [coords, setCoords] = useState(null);
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(
(position) => {
setCoords({
lat: position.coords.latitude,
long: position.coords.longitude,
});
},
(error) => {
console.error(error.message);
}
);
}
return [coords, setCoords];
};
export default useGeoLocAPI;
Since the success callback uses setState , i'm having a hard time trying to mock this hook for testing. I've also heard mocking setState is an anti-pattern, which makes me wonder how I would even do this. I am able to do a simple smoke test by creating the following mock in my setupTests.js
const mockGeolocation = {
getCurrentPosition: jest.fn(),
watchPosition: jest.fn(),
};
global.navigator.geolocation = mockGeolocation;
But because this mock doesn't setState, the hook always returns null in my tests.
Is there a way to properly mock the geolocation API so I can do the following:
- Assert the shape of the state.
- Assert it's error handling
- Assert that it can actually set state
I've created an issue of this in the project's repo in case more information is needed.