Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Here are the steps to simulate/fake navigator.geolocation in a React Jest test:

  1. Install a mock Geolocation API package like mock-geolocation via npm.

  2. Import and initialize the mock Geolocation API at the beginning of your test suite:

import "jest-enzyme";
import { geolocate } from "mock-geolocation";

beforeEach(() => {
  mockGeolocation();
});
  1. Next, implement a test case that calls a function that depends on geolocation data. In this example, let's pretend we have a function called 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,
      },
    });
  });
});
  1. In the mocked 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,
      },
    });
  });
};
  1. Run the Jest test as usual (npm test) and observe the test suites pass!