Here are the steps to simulate/fake navigator.geolocation in a React Jest test:
Install a mock Geolocation API package like mock-geolocation
via npm.
Import and initialize the mock Geolocation API at the beginning of your test suite:
import "jest-enzyme";
import { geolocate } from "mock-geolocation";
beforeEach(() => {
mockGeolocation();
});
getCurrentPosition
that queries the browser for the user's current geographic location. jest.mock("./utils/geolocation.js");
import { getCurrentPosition } from "./utils/geolocation.js";
test("getCurrentPosition returns user's current location", () => {
getCurrentPosition().then((result) => {
expect(result).toMatchObject({
coords: {
latitude: 37.78825,
longitude: -122.4324,
},
});
});
});
getCurrentPosition
function, you can then resolve a promise and return a fake geolocation object. import { geolocate } from "mock-geolocation";
export const getCurrentPosition = () => {
return new Promise((resolve) => {
geolocate({
latitude: 37.78825,
longitude: -122.4324,
});
resolve({
coords: {
latitude: 37.78825,
longitude: -122.4324,
},
});
});
};
npm test
) and observe the test suites pass!Asked: 2022-05-08 11:00:00 +0000
Seen: 12 times
Last updated: Mar 26 '23