Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To simulate navigator.geolocation in a React Jest test, you can use the mockImplementation method of navigator.geolocation to simulate the location data.

First, create a mock implementation of the getCurrentPosition method of navigator.geolocation by defining an object with a getCurrentPosition property, which is a function that takes a success callback and returns the result.

navigator.geolocation = {
  getCurrentPosition: jest.fn()
    .mockImplementation((success) => {
      const position = { 
        coords: {
          latitude: 37.7749,
          longitude: -122.4194
        }
      }
      success(position);
    })
};

Next, in your test, you can access the current position using the navigator.geolocation.getCurrentPosition function.

test('should display current location', async () => {
  const { getByTestId } = render(<MyComponent />);
  const locationElement = getByTestId('location');
  expect(locationElement).toBeInTheDocument();

  // Wait for geolocation to be called and resolved
  await waitFor(() => expect(navigator.geolocation.getCurrentPosition).toHaveBeenCalled());

  // Assert that the location element displays the expected coordinates
  expect(locationElement).toHaveTextContent('37.7749, -122.4194');
});

In this example, MyComponent gets rendered, and we wait for the call to navigator.geolocation.getCurrentPosition to complete. Finally, we check that the location element displays the expected coordinates.