Ask Your Question
4

What is the process of simulating or faking navigator.geolocation in a React Jest Test?

asked 2022-05-08 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-03-26 20:00:00 +0000

lalupa gravatar image

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!
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-05-08 11:00:00 +0000

Seen: 12 times

Last updated: Mar 26 '23