Cypress mock geolocation

Viewed 2887

I'm developing a website using current user geolocation (throught geolocation API)

Is there a way to mock user geolocation (gps position) on cypress (chrome) ? I didn't found anything on that

1 Answers

Yes.

You can stub the geolocation.getCurrentPosition() function from the window object.

cy.visit('/test', {
  onBeforeLoad (win) {
    // e.g., force Barcelona geolocation
    const latitude = 41.38879;
    const longitude = 2.15899;
    cy.stub(win.navigator.geolocation, 'getCurrentPosition').callsFake((cb) => {
      return cb({ coords: { latitude, longitude } });
    });
  },
});

In fact, there is a thread in GitHub talking about this Cypress (desired) feature.

I've posted the solution that works for me using Cypress v4.10.0, feel free to improve the code.

Related