I am new to coding and making a react app. This is part of the code to get the geolocation
const getLocation = () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, {
});
}
};
const errorCallback = (error) => {
switch (error.code) {
case error.PERMISSION_DENIED:
setErrorMessage(error.message);
break;
default:
setErrorMessage("");
break;
}
};
return (
<div>
{errorMessage && <p>{errorMessage}</p>}
</div>
);
}
Then i tests this part with
import { render, screen, waitFor, act } from '@testing-library/react';
import App from './App'; // Adjust the import according to your file structure
// Mock the geolocation API
global.navigator.geolocation = {
getCurrentPosition: jest.fn()
};
test('handles geolocation error', async () => {
// Mock the getCurrentPosition function to return an error asynchronously
navigator.geolocation.getCurrentPosition.mockImplementationOnce((success, error) => {
error({
code: 1,
message: "User denied geolocation prompt"
});
});
render(<App />);
// Wait for the error message to appear
await waitFor(() => {
expect(screen.getByText("User denied geolocation prompt")).toBeInTheDocument();
}, { timeout: 1000 });
});
So the test case is setting the error to be code 1, which is the permission denied error. However, the switch function is going to the default case instead of the permission denied case.
The correct passing of the error is like this:
navigator.geolocation.getCurrentPosition
.mockImplementationOnce((success, error) => Promise.resolve(
error({
code: 1,
message: "User denied geolocation prompt",
PERMISSION_DENIED: 1
})
));